[python]:被 super() 弄糊涂了 [英] [python]: confused by super()
问题描述
可能的重复:
了解 Python super()
B
类是 A
类的子类,所以在 B 的 __init__
中我们应该像这样调用 A 的 __init__
:
Class B
subclasses class A
, so in B's __init__
we should call A's __init__
like this:
class B(A):
def __init__(self):
A.__init__(self)
但是使用 super()
,我看到了这样的东西:
But with super()
, I saw something like this:
class B(A):
def __init__(self):
super(B, self).__init__() #or super().__init__()
我的问题是:
为什么不是
super(B, self).__init__(self)
?仅仅因为返回代理对象是一个绑定对象?
Why not
super(B, self).__init__(self)
? Just because the return proxy object is a bound one?
如果我在 super 中省略了第二个参数并且返回的代理对象是未绑定的,那么我应该写 super(B).__init__(self)
吗?
If I omit the second argument in super and the return proxy object is an unbound one, then should I write super(B).__init__(self)
?
推荐答案
super()
返回基类的一个实例,所以 self
被隐式传递给 __init__()
就像在任何其他方法调用中一样.
super()
returns an instance of the base class, so self
gets implicitly passed to __init__()
like in any other method call.
关于你的第二个问题,这是正确的.在没有实例的情况下调用 super()
作为第二个参数返回对类本身的引用,而不是从您的子类实例构造的实例.
With regards to your second question, that's correct. Calling super()
without an instance as the second argument returns a reference to the class itself, not an instance constructed from your subclass instance.
这篇关于[python]:被 super() 弄糊涂了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!