0

I have a class with 3 attributes:

class Player():
    def __init__(self,pos,stack):
        self.pos = pos
        self.stack = stack
        self.debt = 0

All instances will begin with debt = 0. In my main program I will be modifying these attributes for many instances, but a player's debt can't be greater than a player's stack. Is it a way to prevent (especify) this from the class declaration? . I don't want to write

if player.debt > player.stack:
    player.debt = player.stack

everytime a player's debt is modified. Is it a way to do this automatically from the class Player?

For example, in the following code I want to make the automatic modifications :

jug = Player("BTN",1000)  # jug.debt then must be 0
jug.debt = 500            # jug.debt then must be 500
jug.debt = 2000           # jug.debt then must be 1000

1 Answers1

0

Write a property and in the setter check if it exceeds the limit.

class Player():
    def __init__(self,pos,stack):
        self.pos = pos
        self.stack = stack
        self._debt = 0
    @property
    def debt(self):
        return self._debt
    @debt.setter
    def debt(self, val):
        if val > self.stack:
            val = self.stack
        self._debt = val
wwii
  • 23,232
  • 7
  • 37
  • 77