classmethod & staticmethod

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Tue Jul 24 04:05:06 EDT 2007


james_027 a écrit :
> hi,
> 
> python's staticmethod is the equivalent of java staticmethod right?

IIRC, yes. A 'staticmethod' is in fact nothing more than a function 
attached to a class, and which can be called on the class or an instance 
of. Note that since Python supports modules and functions, staticmethods 
are of little practical use.

> with classmethod, I can call the method without the need for creating
> an instance right? since the difference between the two is that
> classmethod receives the class itself as implicti first argument. 

Yes.

> From
> my understanding classmethod are for dealing with class attributes?

Not necessarily - you can access class attributes from within an 
instance method (but obviously a classmethod cannot access instance 
attributes).

> Can somebody teach me the real use of classmethod & staticmethod?

The 'real' use is (are) the one(s) you'll find. FWIW, I use 
staticmethods for helper functions that don't need access to the class 
or instance but are too specific to a class to be of any use as plain 
functions. Which is not a very frequent case. Classmethods are more 
usefull - mostly as alternate constructors or utility methods for an 
alternate constructor, but there are other possible uses (sorry, I have 
no concrete example at hand).



More information about the Python-list mailing list