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/55871580/

相关文章:

php - 您如何拒绝在 PHP 中创建实例副本?

oop - 确保嵌入式结构实现接口(interface)而不引入歧义

python - LookupError : from nltk. 图书导入*

用于调用 SOAP - Web 服务的 Java 类

python - 对象在动态类型创建期间被子类化,但在 python2 中的经典类定义期间不被子类化

Javascript。什么时候必须在子类声明中使用构造函数?

php - 如何使用 Mysqli 的面向对象方法预填充表单?

python - Python For 循环中的元组和迭代器

python - python 3.5 代码中的变量需要类型注释

python - TensorFlow 缺少 FFT 的 CPU 运算(InvalidArgumentError : No OpKernel was registered to support Op 'FFT' with these attrs)