[python]:被 super() 弄糊涂了 [英] [python]: confused by super()

查看:26
本文介绍了[python]:被 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__()

我的问题是:

  1. 为什么不是super(B, self).__init__(self)?仅仅因为返回代理对象是一个绑定对象?

  1. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆