这符合我的预期;
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, which is what I want.
这不起作用,但我想要它;
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, which isn't what I want.
似乎子类仍指向主类中指定的相同dict对象,但我希望它们具有唯一的dicts。如果不在每个子类中编写fields = {'name':''}
,我该怎么做?
PS-我当然希望使用类级别属性,而不是实例属性,因为我创建的所有实例都将使用此共享'字典。
答案 0 :(得分:3)
最简单的方法是使用元类(我假设使用Python 2.x语法):
Identity
使用中:
class FieldsMeta(type):
def __new__(mcs, name, bases, dict):
"""This controls the 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
参见例如data-model documentation for __new__
:
[
>>> Parent.fields {'name': ''} >>> Child.fields {'name': ''} >>> Child.fields is Parent.fields False >>> Child.fields['name'] = 'Child' >>> Child.fields {'name': 'Child'} >>> Parent.fields {'name': ''}
]也通常在自定义元类中按顺序重写 自定义类创建。
以及customizing class creation上的部分。
答案 1 :(得分:0)
您可以创建字段setter,它将在分配新值之前复制dict
class Foo(object):
fields = {'name':''}
def set_field(self, field, value):
self.fields = dict(self.fields)
self.fields[field] = value
class Bar1(Foo):
pass
class Bar2(Foo):
pass
Bar1.fields['name'] == Bar2.fields['name'] # returns True
# Bar1.fields['name'] = 'Bar1'
Bar1.set_field(Bar1, 'name', 'Bar1')
print(Bar1.fields['name'] == Bar2.fields['name']) # returns False