2017-02-20 26 views
0

基本上,我的問題是問here並有一些答案,像下面,其中Son確實喜歡Father一些東西(在這種情況下,INIT)和一些其他的東西像GrandFatherdo_thing)。調用父母的方法,有什麼後果?

class GrandFather(object): 
    def __init__(self): 
     pass 

    def do_thing(self): 
     # stuff 

class Father(GrandFather): 
    def __init__(self): 
     super(Father, self).__init__() 

    def do_thing(self): 
     # stuff different than Grandfather stuff 

class Son(Father): 
    def __init__(self): 
     super(Son, self).__init__() 

    def do_thing(self): 
     super(Father, self).do_thing() # <-- this line bypasses Father's implementation 

我想知道是否有調用super像(最後一行以上),即,通過比你自己以外的類類型的任何後果。 我的意思是像你的代碼打破在你不期望它的一些奇怪的點。

+0

什麼是尚未涵蓋[這裏](http://stackoverflow.com/questions/5033903/python-super-method-and-calling-alternatives),[這裏](http://stackoverflow.com/questions/222877 /什麼是超級在做蟒蛇)或[這裏](http://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods)? –

+1

@StephenRauch什麼不包括在內?我的問題沒有涵蓋! :D注意,在我的例子中,最後一行是'super(Father,self)'而不是'super(Son,self)'。後者是使用'super'的正常方式,這在您提供的鏈接中已經介紹過了。然而,我的問題是關於前者,我忽略了直接父類,並在祖父類中調用該方法! – Mahdi

回答

0

你問的問題通常會起作用,但它可能並不完全符合你在多重繼承存在時的意圖。舉例來說,如果Son也從一個Mother類(因亂倫也是的Grandfather一個子類)繼承,你會不會讓你從你的最後一行所期望的呼叫:

class GrandFather(object): 
    def do_thing(self): 
     print("Grandfather") 

class Father(GrandFather): 
    def do_thing(self): 
     print("Father") 

class Mother(GrandFather): 
    def do_thing(self): 
     print("Mother") 

class Son(Father, Mother): 
    def do_thing(self): 
     super(Father, self).do_thing() # will print "Mother", not "Grandfather" 

這個問題竟會作物如果在Son子類中添加了多重繼承(例如class GrandSon(Son, Mother): pass,而您的先前定義Son僅從Father繼承),則意外增加。

這可能是也可能不是你想要的。如果您一直想要GrandFather的執行do_thing,您應該明確地調用GrandFather.do_thing(self),而不是嘗試使用super

但是,讓班級繞過他們的父母方法通常不是一個好主意。你可能會更好地服務於重組你的代碼,所以它不是必需的。也許你可以把GrandFather.do_thing的部分分解出來,你希望Son能夠用於單獨的方法。您不需要在Father中覆蓋該方法,則可以不從Father.do_thing中調用該方法。