Chapter 12. Inheritance: For Good or For Worse
[We] started to push on the inheritance idea as a way to let novices build on frameworks that could only be designed by experts.1.
Alan Kay, The Early History of Smalltalk
This chapter is about inheritance and subclassing, with emphasis on two particulars that are very specific to Python:
The pitfalls of subclassing from built-in types
Multiple inheritance and the method resolution order
Many consider multiple inheritance more trouble than it’s worth. The lack of it certainly did not hurt Java; it probably fueled its widespread adoption after many were traumatized by the excessive use of multiple inheritance in C++.
However, the amazing success and influence of Java means that a lot of programmers come to Python without having seen multiple inheritance in practice. This is why, instead of toy examples, our coverage of multiple inheritance will be illustrated by two important Python projects: the Tkinter GUI toolkit and the Django Web framework.
We’ll start with the issue of subclassing built-ins. The rest of the chapter will cover multiple inheritance with our case studies and discuss good and bad practices when building class hierarchies.
Subclassing Built-In Types Is Tricky
Before Python 2.2, it was not possible to subclass built-in types such as
dict. Since then, it can be done but there is a major caveat: the code of the built-ins (written in C) does not call special methods overridden by user-defined classes. ...