What is class method?

castironpi castironpi at gmail.com
Sun Aug 24 10:08:24 EDT 2008


On Aug 24, 3:35 am, MeTheGameMakingGuy <gopsychona... at gmail.com>
wrote:
> 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?
>
> 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.

It is similar to:

class M:  #not correct as shown
  def newmaker( self, x ):
     newinst= self.__class__( arg1, arg2, x )
     return newinst

m1= M()
m2= m1.newmaker( 'abc' )

except you don't need the first instance to do it with.  Notice you
get a new instance of whatever class m1 is an instance of, rather than
necessarily M.

class N( M ):
   pass

m1= N()
m2= m1.newmaker( 'abc' )

m2 is of class N now too.



More information about the Python-list mailing list