Classes with initialization

Michele Simionato michele.simionato at gmail.com
Mon Apr 9 10:16:37 EDT 2007


On Apr 9, 9:26 am, mariano.suarezalva... at gmail.com wrote:
> Hi all,
>
> I'm currently using code similar to this:
>
>   class ClassWithInitialization(type):
>       def __init__(cls, name, bases, dict):
>           type.__init__(name, bases, dict)
>           dict['__class_init__'](cls)
>
>   class A:
>       __metaclass__ = ClassWithInitialization
>
>       def __class_init__(cls):
>           cls.some_attribute = ...
>           ...
>
> in order to get class attributes initialized (since the values of
> these attributes
> need non trivial work to be computed, putting the code that does that
> computation in the class scope ends up with the class having extra
> attributes---the `local' variables used in the computation of the
> values of class attribute; so I'm using __class_init__'s scope to
> contain those variables)
>
> I was wondering: is there a simpler approach to this?

Yes, see http://www.phyast.pitt.edu/~micheles/python/classinitializer.html

> Also: can someone enlighten me as to when code in class scope is run,
> exactly?
> if a class A has a metaclass M, then M.__init__ does not seem to get
> the code in A's class scope in its arguments AFAICS, so I guess that
> code is run before the class is created?
>
> Cheers,
>

__init__ is run after class creation. What does not work exactly?

  Michele Simionato




More information about the Python-list mailing list