Subclasses
Last updated
A library lends books, DVDs and magazines. They're different, but they all have a title and a year, and they're all lent and given back. Writing that shared part three times would mean fixing every mistake three times. In this lesson you'll write it once, in a parent class called LibraryItem, and build Book and DVD on top of it. You'll add what makes each one different, run the parent's set-up with super(), ask an object what kind it is with isinstance, and meet object, the class at the root of every class.
By the end of this lesson you can
- Write a child class that inherits attributes and methods from a parent class
- Add attributes and methods to a child, and run the parent's
__init__withsuper().__init__ - Ask whether an object or class belongs to a family with
isinstanceandissubclass - Say what a class gets from
object, the parent of every class
A parent and its children
Every item in the library has a title and a year. LibraryItem holds that shared part. Then Book and DVD are built on top of it: the name of the class they build on goes in brackets after their own name.
Book and DVD have nothing in them but pass, yet line 18 makes a book with a title and a year, and line 20 calls describe() on it. A child class gets every attribute and method of its parent class: it inherits them. Book has no __init__ of its own, so Book("Dune", 1965) runs LibraryItem's. That's why vars(dune) on line 23 shows a title and a year.
Line 22 shows that dune is a Book, not just a LibraryItem. It has its parent's behaviour, but it is its own kind of object.
The shared code is written once. Fix a mistake in describe() and every book and DVD is fixed with it. You'll meet other names for the same ideas in books and other languages:
| This course says | You may also read | |
|---|---|---|
| The class you build on | parent class | base class, superclass |
| The class built on it | child class | subclass, derived class |
| What the child does | inherits from the parent | extends the parent |
Adding to a child with super().__init__
A child is only worth having if it adds something. A book has an author, and a DVD has a running time in minutes. So each child gets an __init__ of its own.
Once Book has its own __init__, making a book runs that one, and the parent's is skipped. The child has to ask for the parent's set-up itself. super() means "my parent class", so super().__init__(title, year) on line 12 runs LibraryItem.__init__, which sets the title and year. Line 13 then adds what only books have.
- +title: str
- +year: int
- +__init__(title: str, year: int)
- +describe(): str
- +author: str
- +__init__(title: str, year: int, author: str)
- +by_line(): str
- +minutes: int
- +__init__(title: str, year: int, minutes: int)
- Class LibraryItem; attributes: title, year; methods: __init__, describe.
- Class Book; inherits from LibraryItem; attributes: author; methods: __init__, by_line.
- Class DVD; inherits from LibraryItem; attributes: minutes; methods: __init__.
- Lines 11 to 13 take three values, pass two of them up to the parent, and keep the third.
- Lines 15 and 16 add a method only books have.
by_line()callsself.describe(), a method the book inherited, then adds the author. - Line 21 does the same job for
DVD, which addsminuteson line 22.
Lines 28 and 29 show each object holds its parent's attributes and its own. A DVD has no author and no by_line(): what a child adds belongs to that child only. Add print(rivers.by_line()) at the end and run it to see the AttributeError.
Put super().__init__ first in the child's __init__. Then everything the parent sets up is there before the child's own lines use it.
Forgetting super().__init__
Here Book has its own __init__, but someone forgot line 12 from the last step. Press Run and read the error from the bottom up.
Line 16 works: the book has an author, because Book.__init__ set it. Line 17 calls describe(), and on line 7 Python can't find self.title.
Making a book ran Book.__init__ and nothing else. Python doesn't run the parent's __init__ for you once a child has its own, so LibraryItem.__init__ never ran, and the book never got a title or a year. The mistake is in lines 11 and 12, but the error shows up much later, wherever a missing attribute is first read.
To fix it, add super().__init__(title, year) as the first line of Book.__init__, under line 11, and run it again.
isinstance and issubclass
isinstance(item, Book) asks: is this object a Book, or a child of Book? Because a book is a kind of library item, a Book counts as a LibraryItem too.
issubclass(Book, LibraryItem) asks the same question about two classes: is Book built on LibraryItem?
- Line 21 asks each item two questions. Dune is a
Bookand aLibraryItem. Rivers of Ice is aLibraryItembut not aBook. - Line 22 checks the type with
==, and getsFalse.type()gives the object's own class,Book, and that's notLibraryItem. To ask "is this a library item?", useisinstance, which counts children too. - Lines 23 and 24 show family only goes one way: a book is a library item, but a library item isn't necessarily a book.
- Line 25 gives
isinstancea tuple of classes. The answer isTrueif the object is any one of them.
Most of the time you won't need isinstance at all: you call item.describe() and each object answers for itself. The Polymorphism lessons come back to that.
object, the root of every class
Every class you've written since lesson 3.2 had a parent you never wrote. A class with no brackets is built on object, Python's own class at the root of every class. class LibraryItem: means the same as class LibraryItem(object):.
__bases__ (two underscores each side) is a tuple of a class's parents.
- Lines 11 and 12 show the family line:
Book's parent isLibraryItem, andLibraryItem's parent isobject. - Line 13: so
Bookis a subclass ofobjecttoo, through its parent. - Line 14: everything in Python is an object, numbers and text included. Lesson 3.1 said so, and this is what it means.
- Line 15 shows where
==came from in lesson 3.5, before you wrote__eq__.LibraryItemhas no__eq__of its own, butobjectdoes, and every class inherits it. - Line 17 uses that inherited
__eq__, which only says two objects are equal if they're the same object. That's why two books with the same data weren't equal until you wrote your own.
__init__, __str__, __repr__, __eq__ and __hash__ all have plain versions in object. Writing your own in a class replaces the plain one. That's called overriding, and it's the next lesson.
In other languages
This step is optional. It's for anyone who will meet Java or Rust later.
| Python | Java | Rust | |
|---|---|---|---|
| A child class | class Book(LibraryItem): | class Book extends LibraryItem | No inheritance. A Book struct can hold a LibraryItem in a field |
| Running the parent’s set-up | super().__init__(title, year). Forget it and the attributes are missing | super(title, year); in the constructor. Forget it and Java calls the parent’s constructor with no values, or won’t compile | Make the inner value with its own new: LibraryItem::new(title, year) |
| How many parents | Any number (lesson 4.7) | One class, plus any number of interfaces | None. Shared behaviour comes from traits |
| Is it one of these? | isinstance(item, Book) | item instanceof Book | There’s no family to ask about. Code asks what a type can do, with a trait |
| The root of every class | object | Object | None |
C# works like Java here: class Book : LibraryItem, with base(title, year) to run the parent's constructor, and one parent class at most.
Rust has no inheritance at all. A Rust type gets shared data by holding another value inside it, which is called composition, and shared behaviour from traits. Simple Rust 4.1 explains why.
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: Inheritance: derived classes, and isinstance and issubclass
- Built-in Functions: super
- Built-in Functions: isinstance
- Built-in Functions: issubclass
- Built-in Functions: object: the base class of every class
- The Python Language Reference: object.__init__: a child's __init__ must call the parent's itself
- OMG Unified Modeling Language (UML) 2.5.1: the standard the class diagrams follow
- The Java Tutorials: Inheritance: extends, one parent, and Object as the root
- The Java Tutorials: Using the Keyword super: calling the parent’s constructor
- The Rust Programming Language: Inheritance as a Type System and as Code Sharing: Rust has no inheritance