Object-oriented programming · lesson 5 of 17
Parts in this lesson
Aclass Book(LibraryItem):a child class
Bsuper().__init__(title, year)run the parent's set-up
Cisinstance(item, Book)is it one of these?
Dissubclass(Book, LibraryItem)is this class built on that one?
Eobjectthe root of every class

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__ with super().__init__
  • Ask whether an object or class belongs to a family with isinstance and issubclass
  • 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.

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

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:

Two names for everything
This course saysYou may also read
The class you build onparent classbase class, superclass
The class built on itchild classsubclass, derived class
What the child doesinherits from the parentextends 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.

A parent and the child built on it
100%
LibraryItem
  • +title: str
  • +year: int
  • +__init__(title: str, year: int)
  • +describe(): str
Book
  • +author: str
  • +__init__(title: str, year: int, author: str)
  • +by_line(): str
DVD
  • +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__.
Step 2 code main.py
Edit the code, then run it again
  • 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() calls self.describe(), a method the book inherited, then adds the author.
  • Line 21 does the same job for DVD, which adds minutes on 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.

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

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?

Step 4 code main.py
Edit the code, then run it again
  • Line 21 asks each item two questions. Dune is a Book and a LibraryItem. Rivers of Ice is a LibraryItem but not a Book.
  • Line 22 checks the type with ==, and gets False. type() gives the object's own class, Book, and that's not LibraryItem. To ask "is this a library item?", use isinstance, 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 isinstance a tuple of classes. The answer is True if 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.

Step 5 code main.py
Edit the code, then run it again
  • Lines 11 and 12 show the family line: Book's parent is LibraryItem, and LibraryItem's parent is object.
  • Line 13: so Book is a subclass of object too, 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__. LibraryItem has no __eq__ of its own, but object does, 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.

Subclasses in three languages
PythonJavaRust
A child classclass Book(LibraryItem):class Book extends LibraryItemNo inheritance. A Book struct can hold a LibraryItem in a field
Running the parent’s set-upsuper().__init__(title, year). Forget it and the attributes are missingsuper(title, year); in the constructor. Forget it and Java calls the parent’s constructor with no values, or won’t compileMake the inner value with its own new: LibraryItem::new(title, year)
How many parentsAny number (lesson 4.7)One class, plus any number of interfacesNone. Shared behaviour comes from traits
Is it one of these?isinstance(item, Book)item instanceof BookThere’s no family to ask about. Code asks what a type can do, with a trait
The root of every classobjectObjectNone

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.

What does this program print?
class LibraryItem:
    pass


class Book(LibraryItem):
    pass


item = Book()
print(isinstance(item, LibraryItem), type(item) == LibraryItem)
DVD has its own __init__, which sets self.minutes and nothing else. What happens when you read rivers.title?
You write class Member: with no brackets. What is its parent class?

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