I have a question concerning class variables in Python.
I am trying to code a simple Attack class for an RPG, and I need in this class to access variables from my Weapon class and my Character Class, yet all three have no inheritance relationship to one another. And I can't find help online due to all the threads being on inheritance.
Here are the code samples of each 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 ##### Indentation rectified
class Attack(object):
def __init__(self, Weapon, Character):
self.Weapon = Weapon
self.Character = Character
self.Character.hp -= self.Weapon.dmg
When I try to run my program I get the following error:
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
Any idea on how I could access the hp variable from my Character class inside my Attack class ? Ultimately I will also need to access the dmg variable of the Weapon class inside the Attack class.
There's a problem in your indentation of self.Character.hp -= self.Weapon.dmg
. This code should work:
class Attack(object):
def __init__(self, Weapon, Character):
self.Weapon = Weapon
self.Character = Character
self.Character.hp -= self.Weapon.dmg