我对Python中的类变量有疑问。
我正在尝试为RPG编写一个简单的Attack类,我需要在这个类中从我的Weapon类和我的Character Class访问变量,但这三个都没有彼此的继承关系。由于所有线程都在继承,我无法在线找到帮助。
以下是每个类的代码示例:
class Character(pygame.sprite.Sprite):
def __init__(self, hp, image, speed, x, y):
super(Character, self).__init__()
self.image = image
self.rect = self.image.get_rect().move(x, y) #initial placement
self.hp = hp
class Weapon(Item): #Parent class item is a sprite class
def __init__(self, name, value, image, x, y, dmg):
super(Weapon, self).__init__(name, value, image, x, y)
self.dmg = dmg
class Attack(object):
def __init__(self, Weapon, Character):
self.Weapon = Weapon
self.Character = Character
self.Character.hp -= self.Weapon.dmg
UPDATE #####缩进修正
class Attack(object):
def __init__(self, Weapon, Character):
self.Weapon = Weapon
self.Character = Character
self.Character.hp -= self.Weapon.dmg
当我尝试运行程序时,出现以下错误:
File "classes.py", line 136, in <module>
class Attack(object):
File "classes.py", line 141, in Attack
self.Character.hp -= self.Weapon.dmg
NameError: name 'self' is not defined
关于如何从我的Attack类中的Character类访问hp变量的任何想法?最终,我还需要访问Attack类中的Weapon类的dmg变量。
答案 0 :(得分:0)
你的缩进self.Character.hp -= self.Weapon.dmg
存在问题。这段代码应该有效:
class Attack(object):
def __init__(self, Weapon, Character):
self.Weapon = Weapon
self.Character = Character
self.Character.hp -= self.Weapon.dmg