Object-oriented programming · 5 / 26 Theory

Getters, setters and properties

Getters and setters are methods used to read and modify the attributes of an object in a controlled way. For example, to validate a value before saving it.

Getter and setter methods

You can write them as normal methods:

class Person:
    def __init__(self, name, age):
        self._name = name
        self._age = age

    def get_age(self):
        return self._age

    def set_age(self, age):
        if age < 0:
            raise ValueError("Age cannot be negative")
        self._age = age

p = Person("Ana", 30)
p.set_age(31)
print(p.get_age())   # 31

It works, but it is not the usual style in Python.

Properties: the Pythonic way

The @property decorator lets you use a method as if it were a normal attribute. The syntax stays simple and you can add validation whenever you need it:

class Person:
    def __init__(self, name, age):
        self._name = name
        self.age = age          # uses the setter

    @property
    def age(self):
        return self._age

    @age.setter
    def age(self, value):
        if value < 0:
            raise ValueError("Age cannot be negative")
        self._age = value

p = Person("Ana", 30)
p.age = 31          # calls the setter
print(p.age)        # calls the getter: 31
# p.age = -5        # ValueError

Read-only properties

If you only define the getter, the attribute cannot be assigned:

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

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

c = Circle(2)
print(c.area)       # 12.56636
# c.area = 10       # AttributeError

When should I use them?

  • Start with simple public attributes. You do not need getters and setters "just in case".
  • If later you need validation or a calculated value, convert the attribute into a property: the code that uses the class does not change.