Cam
Cam

Reputation: 33

How do I change class object attributes once they've been created in Python?

I am trying to create object attributes which can be modified later depending on user inputs

The gist of it is that I'm trying to make a Text Based RPG with stats. I made the Player a class object with stats like 'HP' 'AC' 'Strength' and the like.

A core part of the game is the stats being able to interact with each other. For instance, a player's 'AC' is calculated by adding 10 and their 'Dex' modifier

I want to let the player choose their 'Dex' so I need to be able to modify the object attributes accordingly

However, Python doesn't seem to recognize the math I put into it.

class Test:
  def __init__(self):
    self.x = 1
    self.y = 2
    self.z = self.x + self.y

test = Test()
test.y = 7
print(str(test.z))

the print gives me '3'

How can I make it so that the it gives me '8'?

Upvotes: 3

Views: 136

Answers (1)

Daweo
Daweo

Reputation: 36510

If you want attribute value computed at access this is task for @property decorator, consider following example:

class Player:
    def __init__(self):
        self.x = 1
        self.y = 2
    @property
    def z(self):
        return self.x + self.y

player1 = Player()
player1.y = 7
print(player1.z)

Output:

8

If you want to know more about decorators in python I suggest reading realpython Primer on python decorators.

Upvotes: 5

Related Questions