Aloizio Macedo Aloizio Macedo - 3 months ago 6
Python Question

How to effectively update the attributes of an object

I am creating a "pet game" in order to train my computing skills in python (that is just an excuse: it is because it is fun).

I decided to do a simple RPG game. For that, I defined the class hero:

class hero:
#Common class for the main character
def __init__(self, name, lvl, str, agi, vit, int, luk, prof):
self.name = name
self.lvl = lvl
self.str = str
self.agi = agi
self.vit = vit
self.int = int
self.luk = luk
self.prof = prof
self.exp = 0
if prof==1:
self.dmg=3*(self.str)+1*(self.agi)
self.skillList=['heavySlash01']
self.strUp=3
self.agiUp=1
self.vitUp=2
self.intUp=1
self.lukUp=1
if prof==2:
self.dmg=1*(self.str)+3*(self.agi)
self.skillList=['doubleAttack02']
self.strUp=1
self.agiUp=3
self.vitUp=1
self.intUp=1
self.lukUp=2
if prof==3:
self.dmg=4*(self.int)
self.skillList=['fireBall03']
self.strUp=1
self.agiUp=1.5
self.vitUp=0.5
self.intUp=3.5
self.lukUp=1.5
self.hp=19*vit


However, I noticed that whenever the hero leveled up, I needed to update all of its status separately. For instance, I needed to manually update the
hero.dmg
. Changing the
agi
,
str
and
int
did not automatically change the
dmg
as I would expect.

My question is then: Is there a way to make the
dmg
automatically update itself, based on its formula?

Answer

Make dmg a property instead of setting in the __init__ function. The __init__ only runs when the instance is initialized, which is why things aren't updating. However, making it a property runs the method whenever the property is accessed.

@property
def dmg(self):
    if prof==1:
        return 3*(self.str)+1*(self.agi)
    if prof==2:
        ...