类型对象 'Enemy' 没有属性 '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):
print(f"The {goblin.name} attacks! Causing {goblin.damage} damage!")
player.health -= Enemy.damage
print(f"You have {player.health}")
goblin = Enemy("goblin",100,20)
class Player:
def __init__(self,health,damage):
self.health = health
self.damage = damage
player = Player(200,40)
goblin.attack()
error:
Traceback (most recent call last):File "c:\Users\user\Desktop\python stuff\project.py", line 10, in attackplayer.health -= Enemy.damage^^^^^^^^^^^^AttributeError: type object 'Enemy' has no attribute 'damage'
我刚开始学编程,不太明白这个错误是什么意思。
我想让终端显示我创建的哥布林造成了伤害,这个伤害是由它的具体实例决定的。哥布林应该造成20点伤害,因为我就是这么写的。我在“敌人”这个类下面写了一个叫“攻击”的方法,里面应该用到这个具体实例的名字和伤害,然后在终端上写出它对玩家造成了多少伤害。但是我却遇到了这个错误。我不太确定该怎么修复它。
1 个回答
1
用self来代替
def attack(self, player):
print(f"The {self.name} attacks! Causing {self.damage} damage!")
player.health -= self.damage
print(f"You have {player.health} health left.")
可能像这样
class Enemy:
def __init__(self, name, health, damage):
self.name = name
self.health = health
self.damage = damage
def attack(self, player):
print(f"The {self.name} attacks! Causing {self.damage} damage!")
player.health -= self.damage
print(f"You have {player.health} health left.")
class Player:
def __init__(self, health, damage):
self.health = health
self.damage = damage
# Create instances
goblin = Enemy("goblin", 100, 20)
player = Player(200, 40)
# Perform attack
goblin.attack(player)