Proper class initialization

Christoph Zwerschke cito at
Thu Mar 2 11:51:46 CET 2006

Steven Bethard wrote:
> I don't run into this often, but when I do, I usually go Jack 
> Diederich's route::
>     class A(object):
>         class __metaclass__(type):
>             def __init__(cls, name, bases, classdict):
>                 cls.sum = sum(xrange(10))

Good idea, that is really nice and readable. Now all the init code is 
defined inline at the top of the class definition.

> But you can also go something more akin to your route::
>     class A(object):
>         def _get_sum():
>             return sum(xrange(10))
>         sum = _get_sum()
> Note that you don't need to declare _get_sum() as a classmethod, because 
> it's not actually a classmethod -- it's getting used before the class 
> yet exists.  Just write it as a normal function and use it as such -- 
> that is, no ``self`` or ``cls`` parameter.

Often it's so simple ;-) But the disadvantage is then that you cannot 
set the class variables directly inside that function. So if you have to 
initialize several of them, you need to define several functions, or 
return them as a tuple and it gets a bit ugly. In this case, the first 
solution may be better.

-- Christoph

More information about the Python-list mailing list