python - 理解 Python super() 和 __init__() 方法

标签 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__() ,我认为这更好一些。标准文档还引用了 guide to using super()这很容易解释。

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

相关文章:

Java 继承 - 父级和子级的成员

python - 使用 lxml 将一个 xml 复制到 python 中的另一个

python - 如何使用 Selenium Python 单击 <a class href > 链接问题

javascript - 如何在没有 jQuery 的情况下向 <html> 元素添加类?

c++ - 尝试在不使用 vector 的情况下在 C++ 中创建同一类的许多对象

php - 从数据库中获取数据是一种获取方法吗?

python - 如何避免不小心弄乱Python中的基类?

python - 使用 pycrypto 时没有名为 'winrandom' 的模块

python - 将唯一 id 分配给 python 中的列表列表,其中重复项获得相同的 id

javascript - 如何将一个类的所有方法绑定(bind)到javascript中的 'this'变量