Reputation: 3
I am trying to update the number of people in the code below by adding one every time an instance of the class is performed, it used to work for me but I tried the code today and it isn't working. Also when i try and print the "User.people" variable it returns what I assume is its address in the memory. Please help me.
class User:
people = int(0)
def __init__(self, first_name, last_name, age):
self.name = first_name + " " + last_name
self.age = age
User.people += 1
def __str__(self):
return f"{self.name} is {self.age} years old"
def __del__(self):
User.people -= 1
def people(self):
print(f"There are now {self.people} in the class and his name is {self.name}")
return self.people
person1 = User("Greg", "Mitchel", 76)
person2 = User("Michael", "Hutton", 16)
print(User.people)
print(person1)
Output:
Traceback (most recent call last):
File "C:/Users/User/Downloads/test.py", line 20, in <module>
person1 = User("Greg", "Mitchel", 76)
File "C:/Users/User/Downloads/test.py", line 8, in __init__
User.people += 1
TypeError: unsupported operand type(s) for +=: 'function' and 'int'
Upvotes: 0
Views: 38
Reputation: 77837
Your error is that you gave the same name to two different class attributes: first, the simple variable; later you redefined people
as an instance method. By the time you try to alter the population count, people
is redefined as a method, so the increment is illegal. Simply change one name:
def report_pop(self):
print(f"There are now {self.people} in the class and his name is {self.name}")
return self.people
Upvotes: 2