如何在其构造函数中使用额外参数正确初始化 dict 的子类?

How to correctly initialise a subclass of dict with extra arguments in its constructor?

使用 不会在字典中产生任何键。例如:

class Foo(dict):
    def __new__(cls, value, extra):
        return super().__new__(cls, value)

    def __init__(self, value, extra):
        dict.__init__(value)
        self.extra = extra

运行 Foo({'a':1}, 1).keys() returns 空字典键 dict_keys([]).

如何在 Python 中正确地子类化带有额外参数的字典?

换行:

dict.__init__(value)

收件人:

dict.__init__(self, value)

还要考虑组合而不是继承,因为您在这里要脱离 dict 的 API(参见 LSP)。