Classes with initialization

mariano.suarezalvarez at gmail.com mariano.suarezalvarez at gmail.com
Mon Apr 9 09:26:23 CEST 2007


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?

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,

-- m




More information about the Python-list mailing list