簡體   English   中英

Python 3類繼承帶參數

[英]Python 3 class inheritance with parameters

所以我有一個類,字符()和子類,npc(字符)。 它們看起來像這樣:

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

然而,當我從'Npc'中調用'Character'中應該存在(或者我認為)的屬性時,比如'name'或'desc'或'attr',我得到一個“不存在/未定義”的錯誤。 我只是不做繼承嗎? 這里發生了什么? 我混淆了屬性和參數嗎?

你的類角色的構造函數是:

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

所以你必須准確的名字和desc當你使npc herited。 因為我個人更喜歡超級,這將是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM