python超类和子类的问题

时间:2018-09-23 10:18:39

标签: python class attributes subclass

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

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'

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

1 个答案:

答案 0 :(得分:0)

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. 武器类在初始化时也缺少健康属性