Python 3 中的 super() 怪异之处
我知道这个问题之前已经讨论过很多次了,但从来没有解释过“幕后”发生了什么。
任何人都可以提供关于为什么在最后一行代码中注释会导致引发错误的详细解释吗?我知道该 object.__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)
I know this has been discussed a number of times before, but there was never an explanation of what's going on "under the hood".
Can anyone provide a detailed explanation as to why commenting-in the last line of code causes an error to be raised? I know that that object.__init__ doesn't take any arguments, but why does the code work when the line is commented out?
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在Python 3中,每个方法都成为一个闭包,并为正在定义的“当前类”添加了一个隐藏值。这是通过
super()
访问的(不带参数)。Super 返回一个使用类的方法解析顺序 (MRO) 的对象,对于 C 实例,该对象在 A 之后有 B。
如果在 MRO 中找不到 B,A 中的
super().__init__
将调用 object。 __init__,您不能向其传递任何参数。您可以通过查看 SomeClass.__mro__ 来查看某个类的 MRO。
虽然主要讨论的是 2.x,但您可能想阅读 http://fuhm.net/super-harmful/< /a>.
In Python 3 every method becomes a closure with a hidden value added for the "current class" being defined. This is accessed by
super()
(with no arguments).Super returns an object which uses the class's Method Resolution Order (MRO), and for C instances this has B after A.
Without finding B in the MRO,
super().__init__
in A will call object.__init__, to which you can't pass any parameters.You can view the MRO for a class by looking at SomeClass.__mro__.
Though mostly talking about 2.x, you may want to read http://fuhm.net/super-harmful/.