Start learning free

LESSON 594 OF 635 · OBJECT-ORIENTED PROGRAMMING

Getters and Setters in Python in Python

Lesson

TL ; DR:

A getter reads a private field. A setter changes it, but only to a value the class allows.

In Python, @property turns a method into the getter. @age.setter turns a second method into the setter. Other code still writes rex.age, as if it were a plain field.


class Dog:
    def __init__(self, age):
        self._age = age

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

    @age.setter
    def age(self, value):
        if value >= 0:
            self._age = value


Full lesson:

In the Access Modifiers lesson, get_name() let other code read self._name. Often other code must change a field too. A setter allows that, and it checks each new value first.

The getter

Write @property on the line above def age(self). Now reading rex.age runs this method, with no parentheses. It returns the private self._age.

The setter

Write @age.setter above a second def age(self, value). Now rex.age = 4 runs that method, with value set to 4.

The rule

A dog's age can't be negative. So the setter changes self._age only when value is 0 or more. After rex.age = -5, the age stays as it was.

Why not a plain field?

With a plain self.age, any code could set the age to -5. Nothing would check it. A property keeps the rule inside the class. The code that uses rex.age stays the same.


Your task

The Dog class keeps its age in self._age. Add an age property to it. Its getter returns self._age. Its setter ignores negative values.

The code below the class creates rex, then reads and sets rex.age.

Expected output:

Rex is 3
Rex is still 3
Rex is 4
STEP 1 OF 3
    Ctrl + Enter to check

    Getters And Setters in Python

    Keep going with Python500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free