2015-10-19 100 views
1

我希望能夠從兩個不同的輸入到其__init__方法中的不同類繼承。我如何正確地從它們繼承?如何從具有不同__init__輸入的多個類繼承?

下面是什麼,我試圖完成一個簡單的例子:

class a: 
    def __init__(self): 
     print("Hello") 


class b(a): 
    def __init__(self): 
     super().__init__() 
     print("World") 


class c: 
    def __init__(self, text): 
     print(text) 


class d(a, c): 
    def __init__(self): 
     super().__init__('Kronos') # <-- This breaks (and understandably so) 

雖然類似多重繼承的其他許多問題(即How does Python's super() work with multiple inheritance?),我正在尋找如何繼承從具有不同輸入的多個類到它們的__init__

+0

的可能的複製[如何Python的超()與多重繼承工作?](http://stackoverflow.com/questions/3277367/how-does -pythons-super-work-with-multiple-inheritance) – electrometro

+0

考慮在你的'__init__'方法中加入一個'* args,** kwargs' –

+0

你可以試試我的編輯 – DreadfulWeather

回答

2

我相信你可以像下面

class d(a,c): 
    def__init__(self,text): 
     a.__init__(self) 
     c.__init__(self,text) 
+0

啊,我們走了。是的,這就是我要找的。對於那些感興趣的人來說,這不僅執行'print'語句,而且如果你有屬性或方法,它們被正確地繼承。 – KronoS

+0

我也會在執行中反轉a和c。使用'super'方法'__mro__'的順序是從左到右。這意味着如果我有一個在'a'和'c'中定義的屬性,'a'會首先解決該屬性,我相信。 – KronoS

+1

這個(與super不同)不能保證繼承樹中的每個類只被初始化一次。看看例子[這裏](https://rhettinger.wordpress.com/2011/05/26/super-considered-super/)。特別是_Practical_Advice_,並使它們都具有相同的接口,或接受kwargs。 –

相關問題