Please provide support with this Class method example
Question:
class Person:
number_of_people = 0
def __init__(self,name):
self.name = name
Person.add_person()
@classmethod
def number_of_people_(cls):
return cls.number_of_people()
@classmethod
def add_person(cls):
cls.number_of_people += 1
p1 = Person('Tim')
p2 = Person('Jill')
print(Person.number_of_people_())
The code above gives
TypeError: 'int' object is not callable
Please help with this!
Answers:
Your TypeError
is because of what you are trying to return in your classmethod:
umber_of_people = 0
def number_of_people_(cls):
return cls.number_of_people() # you are calling the attribute above which is set to 0
Change to:
def number_of_people_(cls):
return cls.number_of_people
class Person:
number_of_people = 0
def __init__(self,name):
self.name = name
Person.add_person()
@classmethod
def number_of_people_(cls):
return cls.number_of_people()
@classmethod
def add_person(cls):
cls.number_of_people += 1
p1 = Person('Tim')
p2 = Person('Jill')
print(Person.number_of_people_())
The code above gives
TypeError: 'int' object is not callable
Please help with this!
Your TypeError
is because of what you are trying to return in your classmethod:
umber_of_people = 0
def number_of_people_(cls):
return cls.number_of_people() # you are calling the attribute above which is set to 0
Change to:
def number_of_people_(cls):
return cls.number_of_people