In this lesson, you will learn how to use the @property decorator to protect your object attributes while keeping your code clean and intuitive.
Why use properties?
Up until now, you have accessed object attributes directly, like my_object.value = 10. While simple, this is risky because it allows users to assign invalid data (like a negative age or an empty name). Usually, programmers solve this by creating "getter" and "setter" methods (e.g., get_value() and set_value()), but these are clunky to use.
Python’s @property decorator allows you to define methods that behave like attributes, giving you the best of both worlds: the clean syntax of direct access and the safety of a validation function.
Implementing a property
To create a property, you define a method that returns the attribute value and decorate it with @property. To create a "setter," you define a second method with the same name, decorated with @name.setter.
Consider this BankAccount class:
class BankAccount:
def __init__(self, balance):
self._balance = balance # The underscore indicates internal use
@property
def balance(self):
return self._balance
@balance.setter
def balance(self, value):
if value < 0:
print("Error: Balance cannot be negative!")
else:
self._balance = value
account = BankAccount(100)
account.balance = -50 # This triggers the setter method
print(account.balance) # This triggers the getter method
How it works
- The Getter (
@property): When you callaccount.balance, Python automatically runs the method decorated with@property. - The Setter (
@balance.setter): When you writeaccount.balance = -50, Python automatically passes-50as thevalueargument to your setter method. - Encapsulation: By using an underscore (e.g.,
self._balance), you signal that the attribute is internal and should only be accessed via the property methods where your validation logic lives.
This approach ensures that your objects remain in a valid state, preventing "garbage" data from breaking your application logic.
Key Takeaway: Use the @property decorator to define getter and setter methods, which allows you to wrap attribute access in validation logic while maintaining a clean, attribute-like syntax.