newbie-question: difference between classmethod and staticmethod in Python2.2

Duncan Booth duncan at NOSPAMrcp.co.uk
Wed Sep 4 17:34:23 CEST 2002


"T. Kaufmann" <merman at snafu.de> wrote in news:3D7619AE.3050605 at snafu.de:

> 
> When should I use staticmethod or classmethod in classes?
> 
> I thought a staticmethod is a classmethod like in C++/ Java?

A staticmethod is like a static method in C++/Java. A classmethod has no 
direct equivalent in C++/Java.

Use a staticmethod when you know which class you want to access as you are 
writing the code.

class C:
    def smethod(newX):
         C.x = newX    	# Update class variable
    smethod = staticmethod(smethod)

Use a classmethod if you have a class hierarchy and want the method to 
operate on the actual class used in the call rather than the class where it 
was defined:

>>> class C:
    def cmethod(cls, newX):
        cls.x = newX
    cmethod = classmethod(cmethod)

>>> class D(C): pass

>>> c = C()
>>> d = D()
>>> c.cmethod(5) # or C.cmethod(5)
>>> print c.x
5
>>> print d.x
5
>>> d.cmethod(42) # or D.cmethod(42) has the same effect.
>>> print c.x
5
>>> print d.x
42

So here we have two separate class variables, one in C and one in D but 
both are set by the same method. It is a fairly specialised and not very 
common requirement to do this. Mostly you probably want a staticmethod 
instead.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list