Using metaclasses to inherit class variables

telesphore4 at gmail.com telesphore4 at gmail.com
Mon May 22 23:27:56 CEST 2006


Sorry for not being clear.

Fresh copies of class vars so the first one is the correct: ('foo',
'bar', [], False)

>>> import copy
>>>
>>> class ClassVars(type):
...     def __init__(cls, name, bases, dict):
...         for name, value in type(cls).classVars.iteritems():
...             if name not in dict:
...                 setattr(cls, name, copy.copy(value))
...
>>> def are(**kwargs):
...     return type('', (ClassVars,), {'classVars':kwargs})
...
>>> class C(object):
...     __metaclass__ = are(name='foo', desc='bar', list=[])
...     name = 'not foo' #<<< Changing a copy only owned by this class
...
>>> class D(C):
...     pass
...
>>> C.name, C.desc, C.list
('not foo', 'bar', []) <<<<<<<<<<<<<<<<<<<<<< Separate copy we changed
>>> D.name, D.desc, D.list, D.list is C.list
('foo', 'bar', [], False) <<<<<<<<<<<<<<<<<<<< Defaults are not changed

Both prints are correct here

Thanks for your help btw.
t4




More information about the Python-list mailing list