What is class method?

Maric Michaud maric at aristote.info
Sun Aug 24 10:42:01 EDT 2008


Le Sunday 24 August 2008 10:32:34 Hussein B, vous avez écrit :
> 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)

As it has been said, it adds polymorphic behavior to static method concept by 
the mean of  a reference to the real class that called it.

>>>[159]: class A(object) :
   .....:     @classmethod
   .....:     def factory(cls, *args) : return cls(*args)
   .....:
   .....:

>>>[160]: class B(A) :
   .....:     def __init__(self, a, b) :
   .....:         print a, b
   .....:
   .....:

>>>[161]: A.factory()
...[161]: <__main__.A object at 0x2b88d0e33710>

>>>[162]: B.factory(1, 2)
1 2
...[162]: <__main__.B object at 0x2b88d0e33bd0>



It is a common advice that staticmethod should not exist in python, as they do 
nothing compared to module level functions, and we should always use 
classmethods in place of them.

> --
> Thank you for your time.
> --
> http://mail.python.org/mailman/listinfo/python-list



-- 
_____________

Maric Michaud



More information about the Python-list mailing list