staticmethod and classmethod

François Pinard pinard at iro.umontreal.ca
Thu May 26 17:46:35 EDT 2005


[Bruno Desthuilliers]
> C Gillespie a écrit :

> > Does anyone know of any examples on how (& where) to use
> > staticmethods and classmethods?

> Here's an example from a ldap lib [...]

I recently had a use case for class methods while converting a PL/I
program to Python: a lot of global declarations, where in many cases,
procs could be regrouped around well identified subsets of globals.

The idea is to create a class for each related group of globals.  The
global declarations themselves become class variables of that class, and
related procs become class methods meant to act on these class variables.

For best clarity and legibility while doing so, one should use all
lowercase class names in such cases, and use `self' instead of `cls' for
the first formal argument of class methods[1].

Then, one use these classes as if they were each the single instance
of a similar class with usual methods.  If one later changes his/her
mind and wants more usual objects, and not allocated statically (!),
merely remove all classmethod declarations, capitalise the first letter
of class names, and create one instance per class into the all lowercase
name of the class.  That's seemingly all.

--------------

[1] I already found out a good while ago, in many other cases unrelated
to this one, but notably in metaclasses, that `self' is often (not
always) clearer than `cls'.  Classes are objects, too! :-)

-- 
François Pinard   http://pinard.progiciels-bpi.ca



More information about the Python-list mailing list