2017-03-21 29 views
0

我正在研究使用oop的代碼庫,並且我相信它是新的。我的問題具體是,爲什麼NewMenuItem不能從File繼承?這個python繼承層次結構是如何工作的? (具體示例)

代碼下鋪的代碼玩:https://codebunk.com/b/350127244/

「」 「建立的類層次和decendants獲取值」 「」

進口檢查

高清自檢():

class Menu(object): 
    def __init__(self): 
     super(Menu, self).__init__() 
     self.value = "Menu" 

class MenuBar(Menu): 
    #having object in there makes it a new style object, which allows us to use super 
    def __init__(self): 
     super(MenuBar, self).__init__() 
     self.value = "MenuBar" 


class File(MenuBar): 
    def __init__(self): 
     Menu.__init__() 
     super(File, self).__init__() 
     self.value = "File" 
     self.FileValue = "File here!" 

    class New(Menu): 
     def __init__(self): 
      Menu.__init__() 
      pass 

     class NewMenuItem(Menu): 
      def __init__(self): 
       """ 
       Q 1- Why do I need self here? 
       Menu.__init__(self) 

       """ 

       Menu.__init__(self) 
       pass 
      def show_vals(self): 
       print(self.value) 
      """ 
      Q 2 -why wont this work? 
      def show_vals2(self): 
       print(self.FileValue) 
      """ 

example = File.New.NewMenuItem() 
example.show_vals() 
""" 
Q 3 - Why do I get this error with this line? 
inspect.getmro(example) 

AttributeError: 'ManageProduct' object has no attribute '__bases__' 
""" 

我試圖瞭解逐行發生了什麼,但我沒有得到的是爲什麼NewMenuItem不能從File繼承。

我試圖硬編碼文件的實例化,像這樣: 文件。 初始化()

但後來我得到一個錯誤,除非我將文件對象:

File.__init__(File()) 

我猜我與掙扎:

-inheritance樹木 -Super類 - 爲什麼我們需要在這種情況下硬編碼實例化

請記住,這是我遇到的代碼。我不確定爲什麼這樣。

回答

0

繼承和範圍是兩個完全不同的東西。 NewMenuItem被定義在類New的範圍內,在類File的範圍內,但它繼承自Menu,它繼承自object。因此,雖然NewMenuItem只能通過類File並再次通過New訪問,但它將繼承Menu中的方法,並且super將參考Menu

+0

非常感謝你! –