2016-04-03 81 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不被調用。這對你的應用程序有什麼不同,但通常不是一件好事。

相關問題