Skip to main content
 首页 » 编程设计

python之从对象继承的类中 super() 和 __init__() 的行为是什么

2025年04月02日16over140

使用具有新类样式的 python 2.7,如果我的类继承自 Object 类,super(ClassName, self).__init__() 的行为是什么?我的意思是,幕后发生了什么?如果我省略它有什么区别?

上面的例子:

  class ClassName(object): 
    """docstring for ClassName""" 
    def __init__(self, arg): 
        super(ClassName, self).__init__() ## The question above is about this super 
        self.arg = arg 
 
 
  class OtherClass(ClassName): 
    """docstring for OtherClass""" 
    def __init__(self, arg, otherArg): 
        super(OtherClass, self).__init__(arg) ## The question below is about this super 
        self.otherArg = otherArg 

如果我省略 super,幕后会发生什么?

谢谢。

请您参考如下方法:

在单继承的情况下,绝对没有。 object.__init__() 确实下蹲。

在multiple inheritance的情况下, 一整个 chain of initialization没有被调用。这对您的应用程序的影响各不相同,但这通常不是一件好事。