Metaclasses and class variables
Thomas Heller
theller at python.net
Thu Aug 4 09:46:58 EDT 2005
Jan-Ole Esleben <esleben at gmail.com> writes:
> Hi!
>
> I am new to this list, and maybe this is a stupid question, but I
> can't seem to find _any_ kind of answer anywhere.
>
> What I want to do is the following:
> I want to insert a class variable into a class upon definition and
> actually use it during definition.
>
> Manually, that is possible, e.g.:
>
> class A:
> classvar = []
> classvar.append(1)
> classvar.append(2)
>
> I don't want to explicitly set the variable, though. My idea was to
> write the following:
>
> class Meta(type):
> def __new__(cls, name, bases, d):
> d['classvar'] = []
> return type.__new__(cls, name, bases, d)
>
> class Test:
> __metaclass__ = Meta
>
> classvar.append(1)
> classvar.append(2)
>
> However, Python complains that the variable isn't defined; it can be
> found in the class dictionary _after_ definition, though, and then it
> can also be used. But where's the conceptual difference (to the manual
> approach)?
classvar is defined AFTER the class has been created. So, this should
work:
class Test:
__metaclass__ = Meta
Test.classvar.append(1)
Thomas
More information about the Python-list
mailing list