2017-04-21 65 views
1

我遇到了一些關於python的多重繼承的問題。如何從多個父類繼承相同的名稱變量?

class TestFather(object): 
    fathers = {} 
    path = "/C" 

    def __init__(self): 
     super(TestFather, self).__init__() 
     # self.fathers = file_to_dict(self.path) 


class TestMother(object): 
    mothers = {} 
    path = "/D" 

    def __init__(self): 
     super(TestMother, self).__init__() 
     # self.mothers = file_to_dict(self.path) 


class TestChild(TestFather, TestMother): 
    def __init__(self): 
     super(TestChild, self).__init__() 


t = TestChild() 
help(t) 

變量路徑將存儲母親和父親的文件目錄。當我打印出父親和母親的詞典時,我注意到母親詞典以某種方式從父親那裏獲取所有信息。在閱讀Guido的博客MRO http://python-history.blogspot.com/2010/06/method-resolution-order.html並觀看Raymond Hettinger 2015年的超級PyCon視頻之後,我意識到TestChild類只從TestFather繼承路徑變量,並完全忽略來自TestMother的路徑變量。

我的問題是,有沒有一種方法可以讓TestChild使用其父母各自的路徑,而不是隻使用MRO較高的路徑。我知道改變變量名稱會起到作用,但正如雷蒙德所說,必須有更好的方法。

回答

0

TestChild不能隱含由於顯而易見的名稱衝突:TestChild.path不能同時具有兩個值。由於您尚未描述您希望TestChild訪問這兩個值的語義,因此我不確定您真正需要哪種解決方案。

但是,您可以擴大__init__功能,存儲內TestChild的名字,只要你喜歡 - 也許一兩個字符串的名單?

相關問題