一个字典子类实例在初始化后是空的。

huangapple go评论81阅读模式
英文:

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']

huangapple
  • 本文由 发表于 2023年8月4日 20:38:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76835982.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定