@propertyis a built-in decorator that allows you to define a method but access it exactly like an attribute.It is used to implement getters, setters and deleters without changing the public interface of your class.
class Wallet:
def __init__(self, balance):
self._balance = balance # Protected attribute holding the actual data
# 1. Getter: Defines the property name. Read-only access.
@property
def balance(self):
print("Fetching balance...")
return self._balance
# 2. Setter: Runs validation checks when data is changed.
@balance.setter
def balance(self, value):
if value < 0:
raise ValueError("Balance cannot be negative!")
print(f"Updating balance to {value}...")
self._balance = value
# ---- Usage ----
my_wallet = Wallet(100)
# Accessing it looks like a variable, but triggers the @property getter method
print(my_wallet.balance)
# Output:
# Fetching balance...
# 100
# Setting it looks like a variable assignment, but triggers the setter validation
my_wallet.balance = 250
# Output: Updating balance to 250...
# This will trigger the ValueError
# my_wallet.balance = -50