python - 使用 __init__() 方法理解 Python 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()这很好解释。

https://stackoverflow.com/questions/576169/

相关文章:

python - 如何将文件逐行读入列表?

python - 如何复制文件?

python - 在 Python 中手动引发(抛出)异常

python - 如何在 Python 中连接两个列表?

android - 有没有办法在 Android 上运行 Python?

python - 将字符串 "Jun 1 2005 1:33PM"转换为日期时间

python - **(双星/星号)和*(星号/星号)对参数有什么作用?

python - 如何将字符串解析为 float 或整数?

python - 如何将列表拆分为大小相等的 block ?

python - 如何克隆列表以使其在分配后不会意外更改?