Classes with initialization
kyosohma at gmail.com
kyosohma at gmail.com
Mon Apr 9 10:02:45 EDT 2007
On Apr 9, 2: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?
>
> 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
As I understand it, class code doesn't get run until you create an
instance of the class and call a method with that instance. I don't
know how to answer your other question though.
Mike
More information about the Python-list
mailing list