Getters and Setters

Providing controlled access to private data with validation.

Introduction

If attributes are private, how do you read or change them safely? Through getter and setter methods. These act as controlled doors to your private data -- they let you add validation and logic whenever data is accessed or modified.

Why Getters and Setters?

  • Validation: Reject invalid values before they are stored (e.g., negative age).
  • Read-only data: Provide a getter without a setter to make data viewable but not changeable.
  • Computed values: A getter can calculate and return a value on the fly.

Manual Getters and Setters

The straightforward approach is to write explicit get_ and set_ methods.

class Student:
    def __init__(self, name, age):
        self.__name = name
        self.__age = age

    def get_age(self):
        return self.__age

    def set_age(self, age):
        if 0 < age < 150:
            self.__age = age
        else:
            print("Invalid age!")

s = Student("Alice", 20)
print(s.get_age())     # 20
s.set_age(21)          # works
s.set_age(-5)          # Invalid age!

This works, but... the syntax is a bit clunky. You have to call s.get_age() instead of the cleaner s.age. Python has a better way.

The Pythonic Way -- @property

The @property decorator lets you define getters and setters that look like regular attribute access. This is the preferred approach in Python.

class Product:
    def __init__(self, name, price):
        self.__name = name
        self.__price = price

    @property
    def price(self):
        return self.__price

    @price.setter
    def price(self, value):
        if value >= 0:
            self.__price = value
        else:
            raise ValueError("Price cannot be negative")

p = Product("Laptop", 999)
print(p.price)      # 999 — looks like attribute access!
p.price = 899       # uses setter with validation
print(p.price)      # 899
# p.price = -100    # raises ValueError

The magic: From the outside, p.price looks like a normal attribute, but behind the scenes, Python calls your getter or setter method. You get clean syntax AND validation.

When to Use @property

Good Use Cases

  • - Validating data before storing it
  • - Making an attribute read-only
  • - Computing a value from other attributes
  • - Logging when data is accessed

Not Needed When

  • - Simple data with no validation needed
  • - No risk from direct access
  • - No computation required

Read-Only Properties

If you define a @property without a setter, the attribute becomes read-only.

class Circle:
    def __init__(self, radius):
        self.__radius = radius

    @property
    def area(self):
        return 3.14159 * self.__radius ** 2

c = Circle(5)
print(c.area)    # 78.53975
# c.area = 100  # AttributeError — read-only!

OOP Terms

  • Getter: A method that returns the value of a private attribute. Provides read access.
  • Setter: A method that sets the value of a private attribute, usually with validation. Provides write access.
  • @property: A Python decorator that lets you define getters and setters with clean, attribute-like syntax.

Best Practices

  • Prefer @property over manual get/set methods -- it is the Pythonic way.
  • Always validate data in setters before storing it.
  • Use read-only properties for computed values like area, total, or average.
  • Raise exceptions (not just print messages) for invalid data in production code.

Common Mistakes

  • Naming the property the same as the private attribute (e.g., self.price and @property def price) -- this causes infinite recursion. Use self.__price for the private attribute.
  • Forgetting to use @propertyname.setter decorator on the setter method.
  • Creating getters and setters for everything -- only add them when you need validation or control.

Practice Exercises

  1. Create a Temperature class with a @property for celsius that rejects values below -273.15 (absolute zero).
  2. Create an Employee class with a read-only employee_id property and a settable salary property that only accepts positive values.
  3. Create a Rectangle class where width and height have setters (positive values only), and area is a read-only computed property.

Summary

  • Getters read private data; setters modify it with validation.
  • Manual getters/setters work but use clunky method-call syntax.
  • @property provides clean, attribute-like syntax with control behind the scenes.
  • Omitting a setter makes a property read-only.