python error when added a function to a class
Question: i just added this function to my class

    
    
    def getTotalPopulation():
            print 'there are {0} people in the world'.format(Person.population)
    

when i call it, i got this error:

    
    
    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)
    

I call it like this:

    
    
     from MyTests import Person
    >>> Person.Person.getTotalPopulation()
    

### for people who need all code

    
    
    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)
    


Answer: you need to make that a classmethod:

change

    
    
     class Person:
         def getTotalPopulation(self):
             return Person.population
    

to:

    
    
     class Person(object):
         @classmethod
         def getTotalPopulation(cls):
             return cls.population
    

that is, add the `@classmethod` decorator right before the `def`.
additionally, the first parameter of a classmethod is conventionally spelled
`cls` instead of `self`; and you should use it in the method body to support
subclasses properly.

That's for python 2, though. For python three, your code works correctly,
because methods can be used implicitly as though they are `staticmethod`s. I
wouldn't particularly reccomend that, though, since you almost never need that
feature, but `classmethod`s are terrifically useful.

