gpt4 book ai didi

python - Python 3 中的 super() 怪异之处

转载 作者:行者123 更新时间:2023-11-28 21:30:36 25 4
gpt4 key购买 nike

我知道这个问题之前已经讨论过很多次了,但从来没有解释过“幕后”发生的事情。

任何人都可以提供关于为什么在最后一行代码中注释会导致引发错误的详细解释吗?我知道该对象 .__init__ 不接受任何参数,但为什么当该行被注释掉时代码可以工作?

class A:
def __init__(self, a):
print("A constructor")
super().__init__(a)
self.a = a
print("A constructor end")

class B:
def __init__(self, b):
print("B constructor")
super().__init__()
self.b = b
print("B constructor end")


class C(A, B):
def __init__(self, x):
super().__init__(x)


c = C(42)
#a = A(33)

最佳答案

在Python 3中,每个方法都成为一个闭包,并为正在定义的“当前类”添加了一个隐藏值。这是通过 super() 访问的(不带参数)。

Super 返回一个使用类的方法解析顺序 (MRO) 的对象,对于 C 实例,B 在 A 之后。

如果没有在 MRO 中找到 B,A 中的 super().__init__ 将调用 object.__init__,但不能向该对象传递任何参数。

您可以通过查看 SomeClass.__mro__ 来查看某个类的 MRO。

虽然主要讨论的是 2.x,但您可能想阅读 http://fuhm.net/super-harmful/ .

关于python - Python 3 中的 super() 怪异之处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2060475/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com