0

I am relatively new to python and am working on a text based rpg game written in python to improve at it. While trying to set my player's attack damage equal to its strength + weaponattack, I keep running into a problem. The two variables don't add.

class player:

    strength = 10
    weaponattack=0
    attack = strength + weaponattack

#other code outside of class

    player.weaponattack = 10
    print(player.attack)

I expect print(player.attack) to output 20, yet it outputs 10. Could someone please tell me how to fix this?

  • Those variables are set upon creating an instance of the class, editing one won't change another.. If you want that effect you could create a function of the class to update ```attack```, and call each time. – Xosrov May 12 '19 at 12:53

1 Answers1

0

There are several problems here, the main one is that you are using class attributes instead of instance attributes (for more info see What is the difference between class and instance attributes?).

Second, attack = strength + weaponattack is evaluated only at definition time. The fact that you later modify weaponattack does not force attack to be re-evaluated (and re-calculated).

A good solution will be to use a property:

class Player:
    def __init__(self):
        self.strength = 10
        self.weaponattack = 0

    @property
    def attack(self):
        return self.strength + self.weaponattack

player = Player()

print(player.attack)
player.weaponattack = 10
print(player.attack)

Outputs

10
20
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • What's weird though is when I do print(player.weaponattack) outside of the class it would still give me the correct output(10). – JWONTSEEIT May 12 '19 at 13:19