Proper class initialization

Larry Bates larry.bates at websafe.com
Wed Mar 1 16:01:48 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?
> 
> -- Christoph

Although I've never had the need for something like this,
this works:

class A:
    sum=0
    for i in range(10):
        sum+=i
    del i

or moving the initialization into __init__ method isn't
terribly inefficient unless are are creating LOTS of
instances of the same class.

class A:
    def __init__(self):
        self.sum=0
        for i in range(10):
            self.sum+=i


or you can do the do it before you instantiate the class

class A:
    def __init__(self, initialvalue=None):
        if initialvalue is not None: self.sum=initialvalue
        else:                        self.sum=0


for i in range(10):
    sum+=i

b=A(sum)
c=A(sum)

-Larry Bates



More information about the Python-list mailing list