当前位置: 代码迷 >> python >> python超类和子类的问题
  详细解决方案

python超类和子类的问题

热度:23   发布时间:2023-07-14 09:49:01.0

我正在尝试为基于文本的游戏构建存储系统。 我编写了以下代码来声明所需的类:

class Item:
def __init__(self, name, count, health, damage):
    self.name = name
    self.count = count


class Weapon(Item):
    def __init__(self, name, count, health, damage):
        super(Weapon, self).__init__(name, count, damage)
        self.damage = damage

class Food(Item):
    def __init__(self, name, count, health, damage):
        super(Food, self).__init__(name, count, damage, health)

为了测试它是否正常工作,我在文件底部添加了以下代码:

Steak = Food("Steak", 4, 1.5, None)
print("You have {} {}s. Each of them gives you {} health points".format(Steak.count,Steak.name,Steak.health))

这导致属性错误说

AttributeError: 'Food' object has no attribute 'health'

我究竟做错了什么? (我是一个上课的初学者)

class Item:
    def __init__(self, name, count, health, damage):
        self.name = name
        self.count = count
        self.health = health
        self.damage = damage


class Weapon(Item):
    def __init__(self, name, count, health, damage):
        super(Weapon, self).__init__(name, count, health, damage)


class Food(Item):
    def __init__(self, name, count, health, damage):
        super(Food, self).__init__(name, count, damage, health)

Steak = Food("Steak", 4, 1.5, None)
print("You have {} {}s. Each of them gives you {} health points".format(Steak.count,Steak.name,Steak.health))

这将为您提供输出:

You have 4 Steaks. Each of them gives you None health points

所做的更改:

  1. 赋予生命值,伤害增加至物品超类
  2. 武器类别在初始化时也缺少健康属性