You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python报错:type object 'Enemy' has no attribute 'damage' 求助

问题分析与修复

错误原因

AttributeError: type object 'Enemy' has no attribute 'damage' 这个错误的意思是:你试图直接访问Enemy类本身的damage属性,但damage是实例专属属性——只有你创建的具体Enemy对象(比如那个哥布林)才有这个属性,Enemy类本身并不具备。

代码里的核心问题

  1. 硬编码实例名称:attack方法里直接写goblin.name和goblin.damage,这会导致这个方法只能给哥布林用,后续如果创建其他敌人(比如兽人),调用该方法就会出错,应该用self指代当前调用方法的实例。
  2. 错误访问类属性:player.health -= Enemy.damage这里,你用类Enemy来访问damage,但damage是每个敌人实例自己的属性,必须用self.damage来获取当前实例的伤害值。

修复后的代码

# attempt at a health system?

class Enemy:
    def __init__(self, name, health, damage):
        self.name = name
        self.health = health
        self.damage = damage
    def attack(self, target):
        print(f"The {self.name} attacks! Causing {self.damage} damage!")
        target.health -= self.damage
        print(f"You have {target.health} health left!")

class Player:
    def __init__(self, health, damage):
        self.health = health
        self.damage = damage

# 创建实例
player = Player(200, 40)
goblin = Enemy("goblin", 100, 20)

# 调用攻击方法,传入玩家作为目标
goblin.attack(player)

额外优化说明

  • 把player作为参数传给attack方法,让这个方法更通用,不管攻击玩家还是其他敌人都能使用,不用依赖全局的player变量。
  • 调整了打印文本,让输出的信息更清晰直观。

内容的提问来源于stack exchange,提问作者graydaking

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 00:39:59