12: Single Inheritance¶
Summary¶
Inheritance is at its most basic about code reuse
- OOP has a number of different philosophies that attempt to motivate its use.
The most common is that classes should model the real world - the domain model
The domain model has to be hierarchial because single inheritance creates class hierarchies; the problem is that the world isn’t a simple hierarchy
The four pillars of OOP are classes, inheritance, encapsulation, and polymorphism
Python allows multiple inheritance, but you can restrict your use of it to single inheritance if you want to
- Inheritance in Python is a simple extension of the way attributes are resolved
First the instance class is created, then the class, then the base class, and then its base class, and so on until the attribute is located
Attributes can be overridden by simplify defining them in the class that inherits
The super() built-in function can be used to return an attribute from the first class in the inheritance chain to define it
The inheritance chain is defined in the class’s __mro__ attribute
- super() works by searching the __mro__ for the first class to define the method
You can specify the class that has the __mro__ to use and the starting class for the search
If you restrict yourself to single inheritance you can dispense with super() and access the attribute directly, but with multiple inheritance this simple approach doesn’t work
Metaclasses can also be a part of an inheritance chain and there are rules for which metaclass is used.
Program¶
Program Output¶