Proper class initialization

gry at ll.mit.edu gry at ll.mit.edu
Thu Mar 2 09:56:09 EST 2006


Christoph Zwerschke wrote:
> Usually, you initialize class variables like that:
>
> class A:
>     sum = 45
>
> But what is the proper way to initialize class variables if they are the
> result of some computation or processing as in the following silly
> example (representative for more:
>
> class A:
>      sum = 0
>      for i in range(10):
>          sum += i
>
> The problem is that this makes any auxiliary variables (like "i" in this
> silly example) also class variables, which is not desired.
>
> Of course, I could call a function external to the class
>
> def calc_sum(n):
>      ...
>
> class A:
>      sum = calc_sum(10)
>
> 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()
>
> However, this does not work, I get
> TypeError: 'classmethod' object is not callable
>
> Is there another way to put an initialization method for the class A
> somewhere *inside* the class A?
Hmm, the meta-class hacks mentioned are cool, but for this simple a
case how about just:

class A:
   def __init__(self):
      self.__class__.sum = self.calculate_sum()
   def calculate_sum(self):
      do_stuff
      return sum_value

Instead of __class__ you could say:
      A.sum = self.calculate_sum()
but that fails if you rename the class.  I believe either works fine
in case of classes derived from A.

-- George Young




More information about the Python-list mailing list