0
0
Pythonprogramming~3 mins

Why Property decorator usage in Python? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could make your class attributes smart without changing how you use them?

The Scenario

Imagine you have a class representing a bank account. You want to control how the balance is accessed and updated, but you end up writing separate methods like get_balance() and set_balance(). Every time you want to read or change the balance, you have to remember to call these methods explicitly.

The Problem

This manual approach is slow and confusing because users of your class must always remember to call the right methods. It also clutters your code with extra method calls, making it harder to read and maintain. If you want to change how the balance is calculated or validated, you must update all these methods separately.

The Solution

The @property decorator lets you write methods that act like simple attributes. This means you can access or update values using natural syntax like account.balance instead of account.get_balance(). It keeps your code clean and lets you add logic behind the scenes without changing how others use your class.

Before vs After
Before
class Account:
    def __init__(self, balance):
        self._balance = balance
    def get_balance(self):
        return self._balance
    def set_balance(self, value):
        if value >= 0:
            self._balance = value
After
class Account:
    def __init__(self, balance):
        self._balance = balance
    @property
    def balance(self):
        return self._balance
    @balance.setter
    def balance(self, value):
        if value >= 0:
            self._balance = value
What It Enables

It enables you to write clean, readable code that controls access to data while keeping a simple and natural interface.

Real Life Example

Think of a thermostat that shows the current temperature. You want to read the temperature easily, but behind the scenes, it might convert sensor data or apply calibration. Using a property lets you get the temperature like a simple value, while the device handles the details invisibly.

Key Takeaways

Properties let methods behave like attributes for easy access.

This keeps code clean and hides complex logic behind simple names.

It improves readability and maintainability of your classes.