Object-oriented programming · lesson 1 of 17
Parts in this lesson
Adune.lend()encapsulation: keep it valid
Bclass DVD(LibraryItem)inheritance: build on what exists
Citem.loan_days()polymorphism: one call, many answers
D@abstractmethodabstraction: what, not how

The four ideas of OOP

Last updated

Stage 3 taught you how to write classes. This stage is about how to design with them. Object-oriented programming, or OOP, rests on four ideas: encapsulation, inheritance, polymorphism and abstraction. In this lesson you'll meet each one in a few lines of the library's code, see the problem it solves, and find out what makes Python's way of doing OOP different from Java's or Rust's.

By the end of this lesson you can

  • Say what object-oriented programming means
  • Name the four ideas of OOP, the problem each one solves, and spot each in library code
  • Read a class diagram: its boxes, types, marks and arrows
  • Explain how Python trusts the programmer where other languages enforce rules

What "object-oriented" means

A program can be organised around its data and the functions that work on it, kept apart. Or it can be organised around objects: each object holds its own data and carries the methods that work on it. That second way is object-oriented programming, or OOP.

Here's the same job, lending a book, done both ways.

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

Both print 0. The difference is where the rule lives. The lend function on line 1 works on any dict, and nothing stops other code changing book["copies"] directly. The Book class keeps the rule with the data it protects. Stage 3 wrote classes like this. OOP is about designing a whole program out of them, and four ideas help.

The four ideas of OOP
IdeaWhat it meansIn the libraryLessons
EncapsulationKeep an object’s data and the code that changes it together, so the object can’t be put in a bad stateA book can’t be lent with no copies left4.2 to 4.4
InheritanceBuild a new class on an existing one, so it gets the parent’s attributes and methodsA DVD is a library item, plus a running time4.5 to 4.8
PolymorphismOne call that each kind of object answers in its own wayitem.loan_days() gives 21 for a book, 7 for a DVD4.9 to 4.12
AbstractionUse something through what it does, without knowing how it does itThe loan desk needs “something with a loan period”, nothing more4.13 and 4.14

Reading a class diagram

Before writing a bigger program, programmers often draw its classes. A class diagram shows each class, what it holds, what it can do, and how the classes are related. It leaves out how each method works. The way of drawing it comes from UML, the Unified Modeling Language: a standard most programmers and textbooks use. The diagrams in this stage, and the one beside Watch it run, all follow it.

Here's the diagram for the code under it.

A class diagram of the code below
100%
Member
  • +name: str
  • #_loans: list[LibraryItem]
  • +__init__(name: str)
  • +borrow(item: LibraryItem)
  • +get_loans(): list[LibraryItem]
  • +count_loans(): int
«abstract» LibraryItem
  • +fine_per_day: int
  • +title: str
  • +year: int
  • +__init__(title: str, year: int)
  • +loan_days(): int
  • +due_after(day: int): int
Book
  • +author: str
  • +__init__(title: str, year: int, author: str)
  • +loan_days(): int
DVD
  • +loan_days(): int
  • Abstract class LibraryItem; attributes: fine_per_day, title, year; methods: __init__, loan_days, due_after.
  • Class Book; inherits from LibraryItem; attributes: author; methods: __init__, loan_days.
  • Class DVD; inherits from LibraryItem; no attributes of its own; methods: loan_days.
  • Class Member; attributes: name, _loans; methods: __init__, borrow, get_loans, count_loans.
  • Member holds many LibraryItem in _loans.
Step 2 code main.py
Edit the code, then run it again

A box is a class. It has three parts, top to bottom:

  • The name. In italics, with «abstract» above it, the class is abstract: you can't make an object from it directly, only from its children. Lesson 4.13 shows how. Other words in « » say what kind of class it is, like «dataclass».
  • The attributes, one a line, as name: type. title: str means every item has a title, and it's text. An underlined attribute belongs to the class itself, shared by all its objects, like fine_per_day on line 5.
  • The methods, as name(values it takes): what it gives back. due_after(day: int): int takes a whole number and gives one back. A method with nothing after its brackets gives back nothing (None), like borrow. A method in italics is abstract: each child must write its own.

The mark at the start of a line says who should use it. + means anyone. # means "this class and its children", which Python writes as a name starting with _, like _loans. − means "only this class", written __name. Python doesn't enforce either one: lesson 4.2 explains why.

An arrow with an open triangle means is a. The class at the tail inherits from the class the triangle points at: a Book is a LibraryItem, and so is a DVD. A child's box lists only what it adds or changes. Book adds author, with an __init__ to set it, and writes its own loan_days. It still has title, year and due_after, from its parent.

A line with a diamond means has a. The class at the diamond holds objects of the class at the other end, in the attribute the line is labelled with. A * means any number of them, in a list. A Member has any number of LibraryItems, in _loans.

The code has no types written in it, so where do str and int come from? Python knows every value's type while the program runs, and the diagram shows the types the values had in this example. In lesson 3.6 you wrote some types out yourself, for a dataclass.

Press Watch it run to see the diagram again, under the values. A box stays faint until Python reaches its class line. While one of its methods runs, the box turns pink and the method is marked. Under each box are the names that hold its objects.

Encapsulation: keep it valid

Encapsulation means an object looks after its own data. Other code asks it to do things, like dune.lend(), and it decides whether that's allowed.

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

The number of copies is kept in _copies. The underscore at the start says "this is the book's own business". Other code reads the count with the getter get_copies() on line 6. There's no setter, so the only way to change the count is lend, which refuses at zero. Lessons 4.2 to 4.4 teach all of this, one piece at a time.

The problem it solves: in 3.P, any line could write dune.copies = -5. Now the rule is in one place, and every change goes through it.

Inheritance: build on what exists

A DVD is a library item, like a book: it has a title and a year. Inheritance lets a new class start from an existing one. class DVD(LibraryItem) means "a DVD is a LibraryItem, plus whatever I add". It gets describe without writing it again.

The classes in the code below: DVD is a LibraryItem
100%
LibraryItem
  • +title: str
  • +year: int
  • +__init__(title: str, year: int)
  • +describe(): str
DVD
  • +minutes: int
  • +__init__(title: str, year: int, minutes: int)
  • Class LibraryItem; attributes: title, year; methods: __init__, describe.
  • Class DVD; inherits from LibraryItem; attributes: minutes; methods: __init__.
Step 4 code main.py
Edit the code, then run it again

LibraryItem is the parent class, and DVD the child. Line 12, super().__init__(title, year), asks the parent to set up the parts it knows about. Then the DVD adds its own minutes. Line 19 confirms a DVD counts as a LibraryItem.

The problem it solves: without it, every kind of item would repeat the same attributes and methods, and a fix to one would need copying to all. Lessons 4.5 to 4.8 cover it.

Polymorphism: one call, many behaviours

A book can be borrowed for 21 days, a DVD for 7 and a magazine for 14. Polymorphism means one call, item.loan_days(), that each kind of object answers its own way. The loop on line 26 doesn't check what kind each item is. It just asks.

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

These three classes don't even share a parent. In Python, any object with a loan_days method will do. That's called duck typing: if it walks like a duck and quacks like a duck, treat it as a duck.

The problem it solves: without it, the loop would need an if for every kind of item, and a new kind would mean finding and changing every one of those ifs. Lessons 4.9 to 4.12 show the ways Python does it.

Abstraction: use it without knowing how

Abstraction means using something through what it does, not how. LibraryItem here promises that every item has a loan period, without saying what it is. @abstractmethod on line 8 marks loan_days as something every child must write. The pass on line 10 is a statement that does nothing. A def must have at least one line under it, and pass fills that place: this method has no body of its own.

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

due_after on line 12 is written once, in the parent, and works for every item, because it only relies on the promise. Try adding LibraryItem("Mystery") to the list on line 26 and run it: Python refuses to make an item that hasn't said what its loan period is. Lessons 4.13 and 4.14 teach two ways to write such promises.

Python's way: trust over enforcement

Java and Rust check most of these rules when the program is compiled, before it runs. Python checks very little, and only when a line runs. Here, a line outside the class changes the book's "own business" anyway.

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

Python runs it and prints -5. The underscore is a request, not a lock. Python programmers have a saying for this: we're all consenting adults here. The language trusts you to respect the conventions, and gives you tools, getter and setter methods, abstract classes, type hints and tests, to add checks where they matter.

In other languages (optional):

OOP in three languages
PythonJavaRust
Private attributesA convention: _name means “don’t touch”. Python doesn’t stop youprivate, enforced by the compilerPrivate by default, enforced by the compiler
InheritanceYes, even from several parentsOne parent class, many interfacesNone. Composition and traits instead
PolymorphismAny object with the right method works, checked when the call runsThrough a shared type, checked when compilingThrough traits, checked when compiling
When a mistake shows upWhen the line runs, or earlier with mypy and testsWhen compilingWhen compiling

Simple Rust 4.1 covers the same four ideas for Rust, including why it leaves inheritance out.

Check what you learned

Four short descriptions of library code: which idea is each one? Then a class diagram to read.

A Member keeps its loans to itself, and the only way to add one is member.borrow(item), which checks the limit first.
class Magazine(LibraryItem): gets title, year and describe() without writing them.
The receipt loop calls item.fine(days_late) on every item, and books, DVDs and magazines each work out their own fine.
The loan desk is written to work with "anything that has a loan period", and never looks at how a loan period is worked out.
A class diagram has a box Magazine with an arrow to LibraryItem, ending in an open triangle at LibraryItem. Its methods part reads + loan_days(): int. What does it say?

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