【问题标题】:Python 3 class inheritance with parameters带参数的 Python 3 类继承
【发布时间】:2014-01-07 06:24:09
【问题描述】:

所以我有一个类 character() 和一个子类 npc(character)。它们看起来像这样:

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

但是,当我从 'Character' 调用应该存在(或者我认为)在 'Npc' 中的属性时,例如 'name' 或 'desc' 或 'attr',我得到一个“不存在/是未定义”错误。我只是没有做继承吗?这里发生了什么?我是否混淆了属性和参数?

【问题讨论】:

    标签: inheritance python-3.x parameters attributes subclass


    【解决方案1】:

    你的类角色的构造函数是:

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

    所以当你继承 npc 时你必须精确的名字和描述。 因为我个人更喜欢 super 这将是:

    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
    

    【讨论】:

    • @Metalgearmaycry - 不要忘记通过单击左侧的向上箭头和绿色褪色的勾号来投票和接受答案。这让每个人都知道你的问题已经解决了:)
    • 我知道这条评论有点晚了,但是有没有办法不使用这些特定参数调用 super().__init__ 方法,而是让它们成为我可以在创建对象时指定的变量班级?类似于:' x = npc("a_greeting","a_topic","a_name","a_desc") ?
    • @James 您可以在npc.__init__(self, greet, topic, name, desc) 中使它们具有相同的参数并调用super().__init__(name, desc)。或者使用**kwargs 并使用关键字 unpack 传递它们会更加灵活和易于编写。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-30
    • 2012-06-26
    • 2020-08-14
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多