Proper class initialization

Jack Diederich jack at performancedrivers.com
Wed Mar 1 21:47:09 CET 2006


On Wed, Mar 01, 2006 at 09:25:36PM +0100, 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:

Yes, it is called a meta class.

> 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

What we normally think of as an instance is an instance of a class.
Classes are actually instances of metaclasses.  What you are looking for
is __init__, but not the __init__ defined after 'class A...' you want
the __init__ that is called when you type 'class A....'

Python 2.4.1 (#2, Mar 30 2005, 21:51:10) 
[GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class MyMeta(type):
...   def __init__(cls, *ignored):
...     cls.sum = 0
...     for (i) in range(10):
...       cls.sum += i
... 
>>> class A(object):
...   __metaclass__ = MyMeta
... 
>>> print A.sum
45
>>> print A.i
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: type object 'A' has no attribute 'i'
>>> 

For something as simple as this example it is easier and cleaner
to move the loop into a function and do the one-liner assignment.
Because the metaclass can do _anything_ to the class the reader
is obliged to go read its code.  The simple assignment from a
function obviously has no side effects.

Hope that helps,

-jackdied



More information about the Python-list mailing list