Getter and Setter Methods

Getter and Setter methods provide a controlled way to read (get) and update (set) an object's attribute values, rather than allowing them to be accessed or modified directly - especially useful for private attributes.

Basic Getters and Setters

class Account:
    def __init__(self, balance):
        self.__balance = balance   # private attribute

    def get_balance(self):
        return self.__balance

    def set_balance(self, amount):
        if amount < 0:
            print("Balance cannot be negative")
        else:
            self.__balance = amount

acc = Account(1000)
print(acc.get_balance())   # 1000
acc.set_balance(2000)
acc.set_balance(-500)      # Balance cannot be negative

The setter method here adds validation logic, preventing the balance from ever being set to an invalid value - something direct attribute access wouldn't allow you to control.

A Cleaner Approach: the @property Decorator

Python's @property decorator lets you define getter and setter logic while still allowing the attribute to be accessed using simple, direct syntax rather than explicit method calls.

class Account:
    def __init__(self, balance):
        self.__balance = balance

    @property
    def balance(self):
        return self.__balance

    @balance.setter
    def balance(self, amount):
        if amount < 0:
            print("Balance cannot be negative")
        else:
            self.__balance = amount

acc = Account(1000)
print(acc.balance)   # 1000, reads like a plain attribute
acc.balance = 2000    # runs the setter logic behind the scenes
The @property approach is generally preferred in modern Python code, since it keeps the clean syntax of direct attribute access while still enforcing validation and control behind the scenes.

Coming Up Next

To close out this module, the final topic brings everything together with a complete Inheritance Case Study.

Ready to Master Data Science?

Join Uncodemy's Data Science Course and build real, job-ready skills with expert mentors.

Explore Course