带有参数的Python 3类继承 [英] Python 3 class inheritance with parameters

查看:308
本文介绍了带有参数的Python 3类继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I have a class, character(), and a subclass, npc(character). They look like this:

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"中的属性时,例如名称","desc"或"attr",我得到一个不存在/是"未定义"错误.我就是不继承继承权吗?这里发生了什么?我会混淆属性和参数吗?

however, when I call an attribute from 'Character' that should exist (or so I think) in 'Npc', like 'name' or 'desc' or 'attr', I get a "does not exist/is undefined" error. Am I just not doing inheritance right? What's going on here? Am I mixing up attributes and parameters?

推荐答案

您的类字符的构造函数是:

the constructor of you class character is :

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

因此,在继承npc时必须精确命名和描述. 由于我个人比较喜欢超级,所以它将是:

so you have to precise name and desc when you make npc herited. As I personnaly prefer super this would be:

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

这篇关于带有参数的Python 3类继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆