Course contentsShow
← Python
Lesson 469 of 1,0607. Object-Oriented ProgrammingFree lesson

Implementing Setters for Data Validation

Create setter methods with property decorators to enforce constraints and ensure data integrity whenever an attribute is modified.

In this lesson, you will learn how to use setter methods with the @property decorator to automatically enforce rules and maintain data integrity whenever an object's attribute is updated.

Why use Setters?

In Python, you can directly access object attributes (e.g., my_obj.value = 10), but this is risky because someone might assign an invalid value, like a negative number where only positives are allowed. A setter acts as a gatekeeper. By defining a setter, you can intercept the assignment process to validate the data before it is stored in the object.

Implementing the Setter

To implement this, you first define a "getter" method with the @property decorator. Then, you define a second method with the exact same name, decorated with @name.setter.

Consider a BankAccount class where we must ensure the balance never drops below zero:

class BankAccount:
    def __init__(self, balance):
        self._balance = balance  # Internal attribute

    @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

# Usage
account = BankAccount(100)
account.balance = 50   # This works perfectly
account.balance = -20  # Raises ValueError immediately!

How it works

  1. The Getter: The @property decorator makes the balance method act like a variable. When you call account.balance, it executes this method.
  2. The Setter: The @balance.setter decorator tells Python that whenever you write account.balance = x, it should jump into this method instead of just overwriting the variable.
  3. Validation: Inside the setter, you have full control. You can check types with isinstance(), verify ranges, or log the change. If the input is invalid, you simply raise an error, preventing the object from entering an inconsistent state.

By keeping the internal storage attribute private (conventionally starting with an underscore, like _balance), you force users to go through your setter, ensuring your validation logic is never bypassed.

Key Takeaway: Using @property and @setter allows you to treat methods like attributes while injecting essential logic to protect your object's data integrity.