What is a class method?

Jean-Michel Pichavant jeanmichel at sequans.com
Tue Aug 24 07:27:47 EDT 2010


Paulo da Silva wrote:
> Em 23-08-2010 04:30, James Mills escreveu:
>   
>> On Mon, Aug 23, 2010 at 12:49 PM, Paulo da Silva
>> <psdasilva.nospam at netcabonospam.pt> wrote:
>>     
>>> I understand the concept of a static method.
>>> However I don't know what is a class method.
>>> Would anybody pls. explain me?
>>>       
>> Please read this first:
>> http://docs.python.org/library/functions.html#classmethod
>>
>> Then ask us questions :)
>>     
>
> I did it before posting ...
> The "explanation" is not very clear. It is more like "how to use it".
>
> Thanks anyway.
>   
A very naive approach:

Instance methodes modify/use the instance. They requires a reference to 
the instance as first parameter (self)

class Foo:
    def foo(self):
        print self.instanceAttribute

Class methodes modify/use the class. They require a class as parameter (cls)

class Foo:
    occurrences = 0
   
    @classmethod
    def foo(cls):
        print "Number of %s occurrences : %s" % (cls.__name__, 
cls.occurrences)


Static methods neither use a class nor an instance, thus require no  
parameter. In that case, the class acts like a namespace (<~>container):

class Foo:

    @staticmethod
    def sayHello():
       print "Hello"

Foo.sayHello()



Cheers,

JM



More information about the Python-list mailing list