2016-04-03 55 views
2

使用Python 2.7的新类的风格,如果我的类从Object类继承,什么是super(ClassName, self).__init__()的行为?我的意思是,幕后发生了什么?如果我省略它,有什么区别?什么是超级的()类继承自Object的行为和__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,什么是发生在幕后?

谢谢。

+0

注意,在'OtherClass'调用'super'并不安全,因为没有保证的MRO隔壁班的允许参数'__init__'(例如,因为它可能是'object')。 – chepner

回答

1

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

multiple inheritance的情况下,一个完整的chain of initialization不被调用。这对你的应用程序有什么不同,但通常不是一件好事。

相关问题