Proper class initialization

Christoph Zwerschke cito at online.de
Wed Mar 1 15:25:36 EST 2006


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?

-- Christoph



More information about the Python-list mailing list