向类添加函数时出现python错误

时间:2014-01-22 19:16:21

标签: python-2.7

我刚把这个功能添加到我的班级

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)

3 个答案:

答案 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