Jump to content

python 3 classes problem

oliverjrose99

when i try and run say "test = person("Test", 99, "99/99/99")",  i get the error "local variable 'population' referenced before assignment". how can i fix this, thanks

 

code:

people = []population = 0class person:    def __init__(self, name, age, dob):        self.name = name        self.age = age        self.dob = dob        people.append(self.name)        population = population + 1        print("%s was born on %s and is currently %s" % (self.name, self.dob, self.age))    def __del__(self):        print("%s has been removed" % (self.name))
Link to comment
Share on other sites

Link to post
Share on other sites

When using a variable in a class it needs to be local (in the class), or global (out of the function).

 

Your variable is global because it is out of the function, and the only way to use variables like the way you are is to add the line "global population" in the top line of the function (or you may be able to use the first line of the class, not the functions, not 100%)

 

Edit: also you may want to fix the line population = population + 1 to "population += 1" since it is the more used format

 

Also noticed that your del function doesn't delete the name from the list, you may want to fix that :P

Intel 3570K - MSI GTX 660Ti 3GB OC Edition - 16GB Corsair LP RAM - ASRock Extreme4 Motherboard - Corsair HX850 - Adata Premier Pro SP900 120GB SSD with Windows 7 - Seagate Barracuda 1TD HDD - Seagate Barracuda 500GB HDD - Thermaltake Frio CPU Cooler - CM Storm Enforcer Case - Macbook Pro Early 2011 Laptop

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×