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.
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.
| Idea | What it means | In the library | Lessons |
|---|---|---|---|
| Encapsulation | Keep an object’s data and the code that changes it together, so the object can’t be put in a bad state | A book can’t be lent with no copies left | 4.2 to 4.4 |
| Inheritance | Build a new class on an existing one, so it gets the parent’s attributes and methods | A DVD is a library item, plus a running time | 4.5 to 4.8 |
| Polymorphism | One call that each kind of object answers in its own way | item.loan_days() gives 21 for a book, 7 for a DVD | 4.9 to 4.12 |
| Abstraction | Use something through what it does, without knowing how it does it | The loan desk needs “something with a loan period”, nothing more | 4.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.
- +name: str
- #_loans: list[LibraryItem]
- +__init__(name: str)
- +borrow(item: LibraryItem)
- +get_loans(): list[LibraryItem]
- +count_loans(): int
- +fine_per_day: int
- +title: str
- +year: int
- +__init__(title: str, year: int)
- +loan_days(): int
- +due_after(day: int): int
- +author: str
- +__init__(title: str, year: int, author: str)
- +loan_days(): int
- +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.
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: strmeans every item has atitle, and it's text. An underlined attribute belongs to the class itself, shared by all its objects, likefine_per_dayon line 5. - The methods, as
name(values it takes): what it gives back.due_after(day: int): inttakes a whole number and gives one back. A method with nothing after its brackets gives back nothing (None), likeborrow. 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.
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.
- +title: str
- +year: int
- +__init__(title: str, year: int)
- +describe(): str
- +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__.
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.
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.
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.
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):
| Python | Java | Rust | |
|---|---|---|---|
| Private attributes | A convention: _name means “don’t touch”. Python doesn’t stop you | private, enforced by the compiler | Private by default, enforced by the compiler |
| Inheritance | Yes, even from several parents | One parent class, many interfaces | None. Composition and traits instead |
| Polymorphism | Any object with the right method works, checked when the call runs | Through a shared type, checked when compiling | Through traits, checked when compiling |
| When a mistake shows up | When the line runs, or earlier with mypy and tests | When compiling | When 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.
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: Classes: the tutorial's whole chapter on classes
- The Python Tutorial: Inheritance
- The Python Tutorial: Private Variables: why Python has no truly private attributes
- Glossary: duck-typing
- The Python Standard Library: abc
- The Python Tutorial: pass Statements
- OMG Unified Modeling Language (UML) 2.5.1: the standard the class diagrams follow: classes, attributes, operations, visibility, generalization and association
- The Java Tutorials: Controlling Access to Members of a Class: private in Java, checked by the compiler
- The Java Tutorials: Inheritance: one parent class in Java, and interfaces
- The Rust Programming Language: Characteristics of Object-Oriented Languages: Rust’s encapsulation, and traits in place of inheritance