What is class method?

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Tue Aug 26 04:56:03 EDT 2008


MeTheGameMakingGuy a écrit :
> On Aug 24, 6:32 pm, Hussein B <hubaghd... at gmail.com> wrote:
>> 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)
>> --
>> Thank you for your time.
> 
> Firstly, don't use method = classmethod(method). Decorators are far
> better. The following code has the same effect:
> 
> class M:
>  @classmethod
>  def method(cls, x):
>   pass
> 
> Far more readable, right?

Yes, but will only work with Python >= 2.4. There are cases where you 
want to keep compatibility with Python 2.3...

> Class methods are useful if you've got lots of inheritance happening.
> The first argument passed in is the class calling the method. Handy
> for a mix-in: it can add methods affecting the actual class it's mixed
> into, rather than messing with the mix-in itself.

I'm not sure I get your point here.

As far as I'm concerned, classmethods are useful anywhere you need to 
work on the class object itself.



More information about the Python-list mailing list