2013-12-18 77 views
4

所以我有一個類character()和一個子類npc(character)。他們是這樣的:Python 3繼承帶參數

class character(): 
    def __init__(self,name,desc): 
     self.name = name 
     self.desc = desc 
     self.attr = ""  
     #large list of attributes not defined by parameters 

class npc(character): 
    def __init__(self,greetings,topics): 
     self.greetings = greetings 
     self.topics = topics 
     character.__init__(self) 
     self.pockets = [] 
     #more attributes specific to the npc subclass not defined by parameters 

然而,當我打電話從「人大」「字符」應該存在(或因此我認爲)的屬性,比如「名」或'desc'或'attr',我得到一個「不存在/未定義」的錯誤。我只是沒有繼承權嗎?這裏發生了什麼?我混合了屬性和參數嗎?

回答

3

你階級性的構造函數是:

class character(): 
    def __init__(self, name, desc): 

所以當你讓NPC herited你必須準確名稱和說明。 正如我personnaly更喜歡超級這將是:

class npc(character): 
    def __init__(self,greetings,topics): 
     super().__init__("a_name", "a_desc") 
     self.greetings = greetings 
     self.topics = topics 
     self.pockets = [] 
     #more attributes specific to the npc subclass not defined by parameters 
+0

這工程!謝謝! – Metalgearmaycry

+0

@Metalgearmaycry - 不要忘記通過點擊左側的向上箭頭和綠色褪色的勾號來上傳並接受答案。這讓大家都知道你的問題已經解決了:) – Joseph