static python classes ?

Alex Martelli aleax at mac.com
Wed Jun 20 11:17:18 EDT 2007


Neil Cerutti <horpner at yahoo.com> wrote:

> In C++ they are used most often for factory functions, since they
> conveniently have access to the class's private members, and
> don't want or need an existing instance. Python seems to have
> adopted this use-case (ConfigParser, for example), but without a
> need for it (code organization?).

What staticmethod does ConfigParser have?  Can't recall one offhand.

I think Python more commonly uses classmethod, rather than staticmethod,
for factories (i.e. a la Smalltalk, not a la C++).  In that case the
advantage wrt a function _is_ there: when you subclass, you can get
instances of the new class, rather than the base class, from the
factory:

>>> class zap(dict): pass
... 
>>> z = zap.fromkeys(range(4))
>>> z
{0: None, 1: None, 2: None, 3: None}
>>> type(z)
<class '__main__.zap'>
>>>

If dict_fromkeys was a plain function (or if fromkeys was a staticmethod
rather than a classmethod of dict) then z would be an instance of dict,
rather than one of zap (unless you also specifically passed the desired
class, kind of cumbersome).


Alex



More information about the Python-list mailing list