我刚把这个功能添加到我的班级
def getTotalPopulation():
print 'there are {0} people in the world'.format(Person.population)
当我打电话给我时,我收到了这个错误:
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: unbound method getTotalPopulation() must be called with Person instance as first argument (got nothing instead)
我称之为:
from MyTests import Person
>>> Person.Person.getTotalPopulation()
class Person:
population = 0
def __init__(self, name, age):
self.name = name
self.age = age
Person.population += 1
print '{A} has been born'.format(A = self.name)
def __str__(self):
return '{0} is {1} years old'.format(self.name, self.age)
def __del__(self):
Person.population -=1
print '{0} is dying :( '.format(self.name)
def getTotalPopulation():
print 'there are {0} people in the world'.format(Person.population)
答案 0 :(得分:1)
你需要制作一个类方法:
变化
class Person:
def getTotalPopulation(self):
return Person.population
为:
class Person(object):
@classmethod
def getTotalPopulation(cls):
return cls.population
即,在@classmethod
之前添加def
装饰器。另外,classmethod的第一个参数通常拼写为cls
而不是self
;你应该在方法体中使用它来正确支持子类。
然而,这是针对python 2的。对于python 3,您的代码可以正常工作,因为方法可以隐式使用,就像它们是staticmethod
一样。但是,我不会特别推荐这一点,因为你几乎从不需要这个功能,但是classmethod
非常有用。
答案 1 :(得分:0)
您需要为实例方法添加self
def getTotalPopulation(self):
答案 2 :(得分:0)
class Person(object):
population = 102
def getTotalPopulation(self):
print '{0} people'.format(self.population)
Person.getTotalPopulation(Person())
class Person(object):
population = 2458
@classmethod
def getTotalPopulation(cls):
print '{0} people'.format(cls.population)
Person.getTotalPopulation()
class Person(object):
population = 3548799
@staticmethod
def getTotalPopulation():
print '{0} people'.format(Person.population)
Person.getTotalPopulation()
结果
102 people
2458 people
3548799 people