python - How to inherit a class attribute that is a dict and make it unique? -
this works expected;
class foo(object): name = '' class bar1(foo): pass class bar2(foo): pass bar1.name == bar2.name # returns true bar1.name = 'bar1' bar1.name == bar2.name # returns false, want.
this doesn't work same, want to;
class foo(object): fields = {'name':''} class bar1(foo): pass class bar2(foo): pass bar1.fields['name'] == bar2.fields['name'] # returns true bar1.fields['name'] = 'bar1' bar1.fields['name'] == bar2.fields['name'] # returns true, isn't want.
it seems subclasses still pointing @ same dict object specified in main class, want them have unique dicts. how can without writing fields = {'name':''}
in each of subclasses?
ps- want use class level attributes, not instance attributes, of instances create use 'shared' dict.
the simplest way using meta-class (i've assumed python 2.x syntax):
class fieldsmeta(type): def __new__(mcs, name, bases, dict): """this controls creation of each new class.""" dict.update(fields={'name': ''}) return type.__new__(mcs, name, bases, dict) class parent(object): __metaclass__ = fieldsmeta class child(parent): pass
in use:
>>> parent.fields {'name': ''} >>> child.fields {'name': ''} >>> child.fields parent.fields false >>> child.fields['name'] = 'child' >>> child.fields {'name': 'child'} >>> parent.fields {'name': ''}
see e.g. data-model documentation __new__
:
[
__new__
] commonly overridden in custom metaclasses in order customize class creation.
and section on customizing class creation.
Comments
Post a Comment