What is class method?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Aug 24 20:08:34 EDT 2008


On Sun, 24 Aug 2008 11:09:46 +0200, Hrvoje Niksic wrote:

> Hussein B <hubaghdadi at gmail.com> writes:
> 
>> Hi,
>> I'm familiar with static method concept, but what is the class method?
>> how it does differ from static method? when to use it? --
>> class M:
>>  def method(cls, x):
>>     pass
>>
>>  method = classmethod(method)
> 
> Use it when your method needs to know what class it is called from.


Ordinary methods know what class they are called from, because instances 
know what class they belong to:

def method(self, *args):
    print self.__class__

You use class methods when you DON'T need or want to know what instance 
it is being called from, but you DO need to know what class it is called 
from:

@classmethod
def cmethod(cls, *args):
    print cls


Why is this useful? Consider the dict method "fromkeys". You can call it 
from any dictionary, but it doesn't care which dict you call it from, 
only that it is being called from a dict:

>>> {}.fromkeys([1, 2, 3])
{1: None, 2: None, 3: None}
>>> {'monkey': 42}.fromkeys([1, 2, 3])
{1: None, 2: None, 3: None}


Any method that behaves like dict.fromkeys() is an excellent candidate 
for classmethod.




-- 
Steven



More information about the Python-list mailing list