Getters, Setters, and Property Decorators
Stryg for at vise menuen
123456789101112131415161718class BankAccount: def __init__(self, balance): self._balance = balance @property def balance(self): return self._balance @balance.setter def balance(self, value): if value < 0: raise ValueError("Balance cannot be negative.") self._balance = value account = BankAccount(100) print(account.balance) # 100 account.balance = 200 print(account.balance) # 200
Property decorators in Python provide a way to control how attributes of a class are accessed and modified. In the BankAccount class, the balance attribute is managed using the @property decorator, which allows you to access balance as if it were a regular attribute, while actually using a method behind the scenes. The @balance.setter decorator lets you define a method that is called when you assign a new value to balance. This approach enables you to add logic, such as validation, whenever the attribute is set. This means you can keep the internal attribute (_balance) private, while exposing a controlled interface to users of the class.
1234567891011121314151617181920212223242526class BankAccount: def __init__(self, balance): self._balance = balance @property def balance(self): return self._balance @balance.setter def balance(self, value): if not isinstance(value, (int, float)): raise TypeError("Balance must be a number.") if value < 0: raise ValueError("Balance cannot be negative.") self._balance = value account = BankAccount(50) try: account.balance = -10 # Raises ValueError except ValueError as e: print(e) # Output: Balance cannot be negative. try: account.balance = "fifty" # Raises TypeError except TypeError as e: print(e) # Output: Balance must be a number.
You should use property decorators when you need to encapsulate attribute access and enforce rules or validation on assignment. This is especially useful when you want to prevent invalid values, log changes, or trigger updates automatically when an attribute changes. Property decorators help you maintain a clean and intuitive interface, allowing users to work with attributes as usual, while you retain full control over how those attributes are managed internally.
Tak for dine kommentarer!
Spørg AI
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat