Proper class initialization
Steven Bethard
steven.bethard at gmail.com
Wed Mar 1 18:10:14 EST 2006
Christoph Zwerschke wrote:
> But I wonder whether it is possible to put all this init code into one
> class initialization method, something like that:
>
> class A:
>
> @classmethod
> def init_class(self):
> sum = 0
> for i in range(10):
> sum += i
> self.sum = sum
>
> init_class()
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))
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.
STeVe
More information about the Python-list
mailing list