在这种情况下是否有必要使用 super().__init__() ?

Is it necessary to use super().__init__() in this case?

编辑: 哦,对不起伙计们。这个问题是重复的,但不是链接问题的重复问题。我在这个问题中找到了我需要的东西,也许我下次应该尝试更多的关键字来搜索。Subclassing dict: should dict.init() be called?

在我的例子中,我在 class StrKeyDict(dict) 中实现了 update__setitem__,而 __new__ 继承自 dict 可能会创建一个空的 dict 来确保 update 可以工作,我认为没有必要再次使用 super().__init__()

代码来自Fluent Python example-code/attic/dicts/strkeydict_dictsub.py

import collections.abc

class StrKeyDict(dict):

    def __init__(self, iterable=None, **kwds):
        super().__init__()
        self.update(iterable, **kwds)

    def __missing__(self, key):
        if isinstance(key, str):
            raise KeyError(key)
        return self[str(key)]

    def __contains__(self, key):
        return key in self.keys() or str(key) in self.keys()

    def __setitem__(self, key, item):
        super().__setitem__(str(key), item)

    def get(self, key, default=None):
        try:
            return self[key]
        except KeyError:
            return default

    def update(self, iterable=None, **kwds):
        if iterable is not None:
            if isinstance(iterable, collections.abc.Mapping):
                pairs = iterable.items()
            else:
                pairs = ((k, v) for k, v in iterable)
            for key, value in pairs:
                self[key] = value
        if kwds:
            self.update(kwds)

当我们使用

d = StrKeyDict(a=1,b=2) 

例如,创建实例d,真实情况是:

1.Call__new__继承自superclassdict创建一个空的dict实例

2.Call __init__ 初始化实例

正如我所说,我在classStrKeyDict(dict)中实现了update__setitem__。那么这里有必要用super().__init__()吗。 谢谢!

总的来说是必须的。而且通常有必要将它作为 init 中的第一个调用。它首先调用父class(dict)的init函数。 它通常创建其底层数据结构。

superclass' __init__() 可能会也可能不会做一些必要的事情来初始化它。如果您知道具体情况,您可以做出明智的决定。如果您不知道最好的办法是调用它以防万一。

现在,如果您不调用它是因为它不是必需的,并且基础 class 的实现发生了变化,因此您必须修复它。

另一方面,在某些情况下调用 superclass __init__() 不是一个好主意,例如,如果它对 superclass 进行非常特定的大量计算并且在 subclass.

中有所不同

FWIW 我的方法总是调用 super().__init__() 除非我有充分的理由不调用它。