python - 使用 __init__() 方法理解 Python super()

标签 python class oop inheritance super

为什么要使用super()

使用 Base.__init__super().__init__ 有区别吗?

class Base(object):
    def __init__(self):
        print "Base created"
        
class ChildA(Base):
    def __init__(self):
        Base.__init__(self)
        
class ChildB(Base):
    def __init__(self):
        super(ChildB, self).__init__()
        
ChildA() 
ChildB()

最佳答案

super() 让您避免显式引用基类,这很好。但主要优势在于多重继承,其中各种 fun stuff可以发生。见 standard docs on super如果你还没有。

请注意 the syntax changed in Python 3.0 :你可以说 super().__init__() 而不是 super(ChildB, self).__init__() ,IMO 更好一些。标准文档还引用了 guide to using super()这很好解释。

关于python - 使用 __init__() 方法理解 Python super(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/576169/

相关文章:

Python - Fine Uploader 服务器端 AWS 版本 4 签名请求

python - Python的哲学 "never is often better than *right* now"是什么意思

.net - 在 .NET 中将成员对象公开为属性或方法

java - 所有java对象都保存在内存中直到以某种方式被销毁吗?

php - 组织类(class) - 帮助 OOP 初学者

javascript - Javascript 中 Singleton 对象的窗口示例?

python - 使用重采样对齐 Pandas 中的多个时间序列

python - 如何检查我在 Python 2.7 中运行的平台 (OS)?

javascript - 在将生成的内容应用于 DOM 之前,将 Javascript 类应用于生成的内容

java - 如何从构造函数中获取值到方法中?