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 raisesValueError - 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.
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.
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.
- Line 15 refuses a negative fine with a
ValueError, aslend()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__, callsself.set_fine(0)instead of settingself._fineitself, 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.
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:
- +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.
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.
days_late(today)(line 12) counts the days from the due date totoday, 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) usesdays_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.
| Kind | Written as | What outside code can set |
|---|---|---|
| Plain attribute | self.fine = 0 | Anything, no checks |
| Getter and setter | get_fine() and set_fine(cents) | Only values the setter accepts |
| Read-only | get_due(), and no setter | Nothing, except through methods like renew() |
| Computed | is_overdue(today), worked out from other values | Nothing: 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:
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.
| Python | Java | C# | Rust | |
|---|---|---|---|---|
| Reading | loan.get_fine() | loan.getFine() | loan.Fine | loan.fine() |
| Setting | loan.set_fine(150) | loan.setFine(150) | loan.Fine = 150 | loan.set_fine(150) |
| Where the check lives | The setter method | The setter method | The property’s set | The setter method |
| Going round the setter | Possible: loan._fine = -50 runs | The compiler refuses: the field is private | The compiler refuses: the field is private | The 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.
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.
- The Python Tutorial: Private Variables: the underscore that marks a value as the object's own
- Built-in Exceptions: ValueError
- Built-in Functions: property: @property and .setter
- PEP 8: Designing for Inheritance: public and non-public attributes, and properties
- OMG Unified Modeling Language (UML) 2.5.1: the standard the class diagrams follow
- The Java Tutorials: Declaring Member Variables: private fields reached through public methods in Java
- C# documentation: Properties: get and set in C#
- The Rust Reference: Visibility and Privacy: private fields and pub methods in Rust