In this lesson, you will learn how to design multi-level inheritance structures to model complex, real-world relationships by chaining derived classes.
Moving Beyond Single Inheritance
So far, you’ve learned how a subclass inherits from a base class. However, real-world systems are rarely that simple. Often, we create an inheritance hierarchy, where a class inherits from a parent that is also a subclass of another class. This allows you to build layers of specialization, where each step down the chain adds more specific behavior.
Building a Hierarchy
Imagine we are modeling a library system. We can start with a general Item, then specialize it into a Book, and finally create a specific type of book, like a Textbook.
class Item:
def __init__(self, title):
self.title = title
class Book(Item):
def __init__(self, title, author):
super().__init__(title)
self.author = author
class Textbook(Book):
def __init__(self, title, author, subject):
super().__init__(title, author)
self.subject = subject
In this structure:
Itemis the base class.Bookinherits fromItem(adding anauthor).Textbookinherits fromBook(adding asubject).
Why Use Hierarchies?
This approach keeps your code organized. Because Textbook inherits from Book, it automatically gains the title attribute (from Item) and the author attribute (from Book) without you having to redefine them. When you call super().__init__() inside Textbook, it travels up the chain: Textbook calls Book, and Book calls Item.
This "chaining" ensures that every class in the hierarchy handles the initialization logic it is responsible for, while the subclass only focuses on adding the unique features that make it special. By structuring your classes this way, you create a clear path of inheritance that reflects how objects relate to one another in the real world.
Key Takeaway: Inheritance hierarchies allow you to build complex systems by chaining classes together, where each level inherits and builds upon the features of its parent, promoting clean and reusable code.