Home > Software design >  access self from a class who got a method from another class
access self from a class who got a method from another class

Time:08-31

The idea is to create an attack class and a hero class and a monster class in Python. The Hero and the Monster will get a specific attack from the attack class and I want to define who is attacked by passing the object in the method. My problem is how I can get access in this method the attributes of the new class.

Let me give an example:

class Hero:
    def __init__(self,health,strength,attack):
        self.health = health
        self.strength = strength
        self.attack = attack

class Monster:
    def __init__(self,health,strength,attack):
        self.health = health
        self.strength = strength
        self.attack = attack

class Attacks:
    def bite(self,who):
        print('I bite')
        who.health -= self.strength #This should be the strength of the one attacking
    def hit(self,who):
        print('I hit')
        who.health -= self.strength #This should be the strength of the one attacking

attacks = Attacks()
my_hero = Hero(100,10,attack = attacks.hit)
my_monster = Monster(100,10,attack = attacks.bite)

print(my_monster.health)
my_hero.attack(my_monster)
print(my_monster.health)

This is not working as it doesn't know in the class attacks self.strength. if I use a number instead then it works:

class Attacks:
    def bite(self,who):
        print('I bite')
        who.health -= 10
    def hit(self,who):
        print('I hit')
        who.health -= 10

This is working fine but then I lose the flexibility to access the strength of the one attacking.

CodePudding user response:

Consider a design like this, which does work. Both player types derive from a common subclass, since their behavior is identical. I have called the member "attacks", since you will probably want to have multiple attacks eventually. The attack method can choose one at random.

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

    def attack(self,other):
        self.attacks( self, other )

class Hero(Player):
    pass

class Monster(Player):
    pass

def biteattack(attacker, victim):
    print('I bite')
    victim.health -= attacker.strength

def hitattack(attacker, victim):
    print('I hit')
    victim.health -= attacker.strength

my_hero = Hero(100,10,biteattack)
my_monster = Monster(100,10,biteattack)

print(my_monster.health)
my_hero.attack(my_monster)
print(my_monster.health)
  • Related