在这种情况下是否有必要使用super().__ init __()? [重复]

时间:2023-02-11 20:55:57

This question already has an answer here:

这个问题在这里已有答案:

EDIT: Oh, sorry guys. This question is a duplicate one, but not the dup of the linked one. I've found what i need in this question, maybe i should try more key word to search next time.Subclassing dict: should dict.init() be called?

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

In my case, I implement update, __setitem__ in the class StrKeyDict(dict), and __new__ inherited from dict may create a empty dict to ensure update can work, I don't think it's necessary to use super().__init__() again.

在我的例子中,我在类StrKeyDict(dict)中实现update,__ setitem__,并且从dict继承的__new__可能会创建一个空的dict以确保更新可以工作,我认为不必再使用super().__ init __() 。

The code is from Fluent Python example-code/attic/dicts/strkeydict_dictsub.py

代码来自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)

When we use

当我们使用

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

for example, to create instance d, the real happening is:

例如,要创建实例d,真正发生的事情是:

1.Call __new__ which inherited from the superclass dict to create a empty dict instance

1.Call __new__继承自超类dict以创建一个空的dict实例

2.Call __init__ to initialize the instance

2.Call __init__初始化实例

Just like I said, I implement update, __setitem__ in the class StrKeyDict(dict). So is it necessary to use super().__init__() here. Thank you!

就像我说的,我在类StrKeyDict(dict)中实现了update,__ setitem__。所以有必要在这里使用super().__ init __()。谢谢!

2 个解决方案

#1


1  

The superclass' __init__() might or might not be doing something necessary to initialise it. If you know what's the case you can make an informed decision. If you don't know your best bet is to call it just in case.

超类'__init __()可能会或可能不会执行必要的操作来初始化它。如果你知道是什么情况,你可以做出明智的决定。如果您不知道最好的选择是为了以防万一。

Now if you don't call it because it is not necessary and the implementation of the base class changes in a way that make it necessary then you will have to fix it.

现在,如果你没有调用它,因为它没有必要,并且基类的实现以一种必要的方式改变,那么你将不得不修复它。

On the other hand there are a few cases where calling the superclass __init__() is a bad idea, for example if it does heavy calculations very specific to the superclass and that are different in the subclass.

另一方面,有一些情况下调用超类__init __()是一个坏主意,例如,如果它执行非常特定于超类的重度计算并且在子类中是不同的。

FWIW my approach is always call super().__init__() unless I have a good reason not to call it.

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

#2


1  

In general it is necessary. And it's often necessary for it to be the first call in your init. It first calls the init function of the parent class (dict). It typically creates its underlying data structure.

一般来说,这是必要的。而且通常需要将它作为init中的第一个调用。它首先调用父类(dict)的init函数。它通常会创建其底层数据结构。

#1


1  

The superclass' __init__() might or might not be doing something necessary to initialise it. If you know what's the case you can make an informed decision. If you don't know your best bet is to call it just in case.

超类'__init __()可能会或可能不会执行必要的操作来初始化它。如果你知道是什么情况,你可以做出明智的决定。如果您不知道最好的选择是为了以防万一。

Now if you don't call it because it is not necessary and the implementation of the base class changes in a way that make it necessary then you will have to fix it.

现在,如果你没有调用它,因为它没有必要,并且基类的实现以一种必要的方式改变,那么你将不得不修复它。

On the other hand there are a few cases where calling the superclass __init__() is a bad idea, for example if it does heavy calculations very specific to the superclass and that are different in the subclass.

另一方面,有一些情况下调用超类__init __()是一个坏主意,例如,如果它执行非常特定于超类的重度计算并且在子类中是不同的。

FWIW my approach is always call super().__init__() unless I have a good reason not to call it.

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

#2


1  

In general it is necessary. And it's often necessary for it to be the first call in your init. It first calls the init function of the parent class (dict). It typically creates its underlying data structure.

一般来说,这是必要的。而且通常需要将它作为init中的第一个调用。它首先调用父类(dict)的init函数。它通常会创建其底层数据结构。