0znygt
0znygt

Reputation: 3

How to change instance variable when another related instance variable is changed in a class?

I recently try to code a text based game. I want to change player proficiency when player level up. How should I change my code for this?

class Player:
    def __init__(self,name,_class,_race):
        self.name = name
        self.level = 1
        self.proficiency = (int(self.level/3)+1)*2
        self.inventory = 0
        self.skills = returnSkills()
        self.stats = returnStats()
        self._class = _class
        self._race = _race
        self.exp = 0

    def levelUp(self):
        self.level+=1


newPlayer = Player("Player","Barbarian","Human")

print(newPlayer.level)

for i in range(10):
    print(newPlayer.level)
    print(newPlayer.proficiency)
    newPlayer.levelUp()

Upvotes: 0

Views: 42

Answers (2)

ericstevens26101
ericstevens26101

Reputation: 121

You can recalculate the proficiency attribute directly in the levelUp() function. Once you have updated the level attribute, that new value of level will be used to calculate the new proficiency.

    def levelUp(self):
        self.level+=1
        self.proficiency = (int(self.level/3)+1)*2

Upvotes: 1

khelwood
khelwood

Reputation: 59114

You could make proficiency a property, so it is calculated from the current level each time it is referenced.

class Player:
    def __init__(self,name,_class,_race):
        self.name = name
        self.level = 1
        self.inventory = 0
        self.skills = returnSkills()
        self.stats = returnStats()
        self._class = _class
        self._race = _race
        self.exp = 0

    @property
    def proficiency(self):
        return (int(self.level/3)+1)*2
    ...

or you could leave it as a plain attribute, and recalculate it inside your levelUp method.

Upvotes: 0

Related Questions