Object-oriented programming · lesson 3 of 17
Parts in this lesson
Aget_fine()a getter: hands the value out
Bset_fine(cents)a setter: checks, then stores
Cget_due()read-only: a getter, no setter
Dis_overdue(today)worked out each time
E@propertythe same, read like an attribute

Getters and setters

Last updated

A loan's fine starts as a plain attribute, and nothing stops it going below zero. In this lesson you'll put the fine behind two methods: a getter, get_fine(), that hands it out, and a setter, set_fine(), that checks every new value first. You'll see what happens when code goes round the setter, give a loan a due date that can be read but not set, work out whether a loan is overdue on a given day, and meet @property, the other way you'll see this written.

By the end of this lesson you can

  • Write a getter, get_x(), that hands out a value the object keeps in _x
  • Write a setter, set_x(), that checks a new value and raises ValueError
  • Make a value read-only with a getter and no setter, and work a value out with a method
  • Read the same getter and setter written with @property

Start with a plain attribute

Here's a Loan with a fine, in cents, as a plain attribute. The item and the member are plain text here, to keep the example short. The desk charges Sam 150 cents, then takes off 200 by mistake. Run it.

Step 1 code main.py
Edit the code, then run it again

Line 15 takes the fine below zero, and nothing stops it: Sam now "owes" -50 cents. A fine should never be negative, and as long as any line of the program can set loan.fine to anything, there's nowhere to put that rule.

The fix is the one lesson 4.2 pointed to: keep the number as the loan's own business, and let other code reach it only through methods.

A getter

The loan now keeps its fine in _fine (line 9), with the underscore from lesson 4.2. Other code reads it with a method, get_fine(), which hands it out. A method that only hands out a value is called a getter.

Step 2 code main.py
Edit the code, then run it again

Lines 16 and 17 call loan.get_fine(), with brackets, wherever they used to write loan.fine. A getter looks like more work than an attribute for the same number. What it buys you is a door: every read goes through the loan's own code. On its own it changes nothing, but it's half of the pair.

A setter that checks

A setter is the other half: a method other code calls to change the value. It gets the new value, checks it, and only then stores it.

Step 3 code main.py
Edit the code, then run it again
  • Line 15 refuses a negative fine with a ValueError, as lend() refused to lend with no copies in lesson 3.3.
  • Line 17 stores the value, but never more than 500 cents, the most a fine can be (lesson 1.P). min() gives the smaller of two numbers.
  • Line 9, in __init__, calls self.set_fine(0) instead of setting self._fine itself, so even the starting value goes through the check.

Line 24 reads the fine, takes off 200, and asks to set -50: the setter refuses, and the fine stays at 150. Line 27 asks for 900 and gets 500. The rule lives in one place, set_fine, and every change goes through it.

Going round the setter

Here's the same loan. This time the line that takes off 200 sets _fine itself, instead of calling set_fine. It's even inside a try, ready for the ValueError. Run it.

Step 4 code main.py
Edit the code, then run it again

A setter only protects the value if code uses it. Outside a class, never write to an attribute that starts with an underscore: call the method that's there for it.

Read-only and computed values

A value with a getter and no setter is read-only to other code. A loan's due date is fixed when the loan is made, so it gets get_due() and nothing else. If the date should change sometimes, a method changes it by the rules. This library lets a member renew a loan once, for another 21 days:

A loan whose due date changes only through its methods
Loan
  • +item: str
  • +member: str
  • #_due: date
  • #_renewed: bool
  • +__init__(item: str, member: str, due: date)
  • +get_due(): date
  • +renew()
  • Class Loan; attributes: item, member, _due, _renewed; methods: __init__, get_due, renew.
Step 5 code main.py
Edit the code, then run it again

renew() on line 14 is the only code that changes _due, and it refuses a second time (line 16). Its name says what's happening, which a set_due() never could.

Watch out for one mistake with getters. Writing loan.get_due = date(2026, 4, 30) doesn't change the date: it puts a date on that one loan under the name get_due, hiding the method. The next loan.get_due() stops with TypeError: 'datetime.date' object is not callable.

Some values aren't stored at all: they're worked out each time you ask. Whether a loan is overdue depends on the day you ask, so the day is passed in.

Step 5 code main.py
Edit the code, then run it again
  • days_late(today) (line 12) counts the days from the due date to today, the date sum from lesson 2.7. max(..., 0) turns a negative count, for a loan that isn't due yet, into 0.
  • is_overdue(today) (line 15) uses days_late. Methods can call each other.
  • get_fine(today) (line 18) is 25 cents a day, at most 500, the 1.P rule. In step 3 the desk set the fine by hand. Here it's worked out from the date, so there's nothing to set.

Line 3 fixes "today" as a constant, so this example prints the same thing every day you run it. Passing the day in also means any day can be asked about: line 33 asks whether Emma will be overdue on 2 April. A real program would pass in date.today(), and the library system's tests will pass in whatever date they need.

Four kinds of value
KindWritten asWhat outside code can set
Plain attributeself.fine = 0Anything, no checks
Getter and setterget_fine() and set_fine(cents)Only values the setter accepts
Read-onlyget_due(), and no setterNothing, except through methods like renew()
Computedis_overdue(today), worked out from other valuesNothing: there’s nothing stored to set

The @property way

Much of the Python code you'll read writes a getter and setter another way, with @property. It's a decorator, like @classmethod in lesson 3.4. The getter is a method named after the value, with @property above it, and the setter has the same name, with @fine.setter above it. Here's step 3's fine written that way:

Step 6 code main.py
Edit the code, then run it again

The checks are the same. What changes is how other code uses them: line 18 sets loan.fine = 150 with no method call, and Python runs the setter. Line 19 reads loan.fine with no brackets, and Python runs the getter. Line 21 reads, takes off 200, and sets, so the setter refuses -50.

This course uses get_ and set_ methods, so you can always see where a method runs. When you meet @property in other code, read it as a getter and setter in disguise.

In other languages

This step is optional. It's for anyone who will meet Java, C# or Rust later.

Getters and setters in four languages
PythonJavaC#Rust
Readingloan.get_fine()loan.getFine()loan.Fineloan.fine()
Settingloan.set_fine(150)loan.setFine(150)loan.Fine = 150loan.set_fine(150)
Where the check livesThe setter methodThe setter methodThe property’s setThe setter method
Going round the setterPossible: loan._fine = -50 runsThe compiler refuses: the field is privateThe compiler refuses: the field is privateThe compiler refuses outside the module

Java writes getters and setters just as this lesson does, named getFine() and setFine(). C# has properties, which work like Python's @property: loan.Fine = 150 runs a setter. Rust uses methods, like Java. In all three, a private field can't be set from outside, so step 4's mistake wouldn't compile. Simple Rust 4.2 writes a getter and a setter that keeps a volume between 0 and 100.

Check what you learned

Three questions. Pick or type an answer, then check it.

What does this program print?
class Loan:
    def __init__(self):
        self.set_fine(0)

    def get_fine(self):
        return self._fine

    def set_fine(self, cents):
        self._fine = min(cents, 500)


loan = Loan()
loan.set_fine(300)
loan.set_fine(loan.get_fine() + 300)
print(loan.get_fine())
A Loan has get_fine() and set_fine(cents), which refuses negative fines. Outside the class, a program runs loan._fine = -50. What happens?
Whether a loan is overdue depends on the day. How should a Loan answer it?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Python