英文:
A dict subclass instance is empty after initialization
问题
我尝试继承一个字典类,通过在初始化期间实现一些逻辑来实现。为此,我在__init()__
方法中添加了一些键值对。
然而,在初始化后,我的子类实例始终为空。
import copy
class my_dict(dict):
def __init__(self, raw_dict):
self = copy.deepcopy(raw_dict)
self['bar'] = raw_dict['foo']
原始字典为{'foo': 'apple'}。
创建my_dict实例时,输出为空字典,但期望的结果应该是:
[{'foo': 'apple', 'bar': 'apple'}]
我该如何实现期望的行为?
英文:
I try to inherit a dict class, by implementing some logic during the initialization. To do so I add some of the key-value pairs in __init()__
method.
However, after initialization, the instance of my child class is always empty.
import copy
class my_dict(dict):
def __init__(self, raw_dict):
self = copy.deepcopy(raw_dict)
self['bar'] = raw_dict['foo']
original = {'foo' : 'apple'}
alfa = my_dict(original)
print(alfa)
prints empty dict while the expectation would be
[{'foo': 'apple', 'bar': 'apple'}]
How can I achieve the desired behaviour?
答案1
得分: 1
你可以使用super构造函数来实现你想要的效果:
import copy
class my_dict(dict):
def __init__(self, raw_dict):
super().__init__(copy.deepcopy(raw_dict))
self['bar'] = raw_dict['foo']
英文:
You can use the super constructor to do the effect you are looking for:
import copy
class my_dict(dict):
def __init__(self, raw_dict):
super().__init__(copy.deepcopy(raw_dict))
self['bar'] = raw_dict['foo']
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论