gnr*_*gnr 5 inheritance dictionary class python-3.x
我正在寻找一种干净,简单的方法来更新继承自基类的类级字典.例如:
class Foo(object):
adict = {'a' : 1}
class Bar(Foo):
adict.update({'b' : 2}) # this errors out since it can't find adict
Run Code Online (Sandbox Code Playgroud)
以便:
Foo.adict == {'a' : 1}
Bar.adict == {'a' : 1, 'b' : 2}
Run Code Online (Sandbox Code Playgroud)
我不想在这里使用实例,如果可能的话也不使用类方法.
小智 5
请注意,即使这样可行,您也可以更新相同的字典而不是创建新的字典(因此Foo.adict is Bar.adict也是如此Foo.adict == Bar.adict).
在任何情况下,最简单的方法是显式引用父类的dict(并复制它,见上文):
class Bar(Foo):
adict = dict(Foo.adict)
adict.update({'b': 2})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2383 次 |
| 最近记录: |