python - 子类、意外参数和 Unresolved 引用的问题

标签 python python-3.x class subclass superclass

所以我正在尝试制作一个无尽的文本冒险游戏(使用this网站的帮助),但我的类(class)遇到了一些问题:

class Item:
def __init__(self, name, desc, usable, value):
    self.name = name
    self.desc = desc
    self.usable = usable
    self.value = value

def __str__(self):

    return "{}\n=====\n{}\nValue: {}\n".format(self.name, self.desc, self.usable, self.value)


class Weapon(Item):

    def __init__(self, damage):
        self.damage = damage
        super().__init__(desc, name, usable, value)

    def __str__(self):
        return "{}\n=====\n{}\nValue: {}\nDamage: {}".format(self.name, self.damage, self.desc, self.usable, self.value)


class BrokenSword(Weapon):

    def __init__(self):
        super(Weapon, self).__init__(name="Broken Sword",
                                     desc="A sword that didn't resist time.",
                                     value=1,
                                     usable=0,
                                     damage=1)

PyCharm 声明 Weapon 类中的 desc、name、usablevalue(在 super().__init__() 内) )是 Unresolved 引用,并且它们是 BrokenSword(Weapon) 类中的意外参数。该代码与教程一非常相似,那么它有什么问题呢?该教程是用 python 2.x 编写的吗?如何修复我的代码?

最佳答案

Weapon 类不知道这些参数是什么。你必须在本地定义它们,或者-上帝禁止-全局定义它们。所以 Weapon.__init__ 应该接受参数:

class Weapon(Item):
    def __init__(self, desc, name, usable, value, damage):
        super().__init__(
            desc=desc,
            name=name,
            usable=usable,
            value=value
        )
        self.damage = damage

关于python - 子类、意外参数和 Unresolved 引用的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46976909/

相关文章:

javascript - 这不是 javascript 类构造函数中定义的错误?

Java Kryonet 发送对象时出错

python - 在 pygame 中进行多个循环的更好方法是什么?

python-3.x - H2OConnectionError : Unexpected HTTP error: HTTPConnectionPool(host ='localhost' , 端口=54321):

python - 标准 Python 基类作为任意属性的容器

python - 按元素对列表求和组合

python-3.x - 如何使用 AWS Lambda 在 AWS Sagemaker 中远程启动 Jupyter Notebook

java - java类和jar的区别

python - 是否可以在开发服务器上测试 Google App Engine OpenID 身份验证?

python - 使用 python sleep 模块时发生了什么?