Sub topic 8
Reusing and overriding behavior with inheritance
This chapter assumes you can define a class, write __init__ and instance methods, and know how instance attributes differ from class attributes. Here you will see how one class can build on another.
What inheritance does
Inheritance lets a new class, the subclass, start with the attributes and methods of an existing class, the parent (or base) class. You write the subclass as class Child(Parent):. The subclass can then add new behavior or override inherited behavior.
Use inheritance for an "is-a" relationship. A dog is an animal, so Dog can inherit from Animal.
A first hierarchy
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "..."
class Dog(Animal):
def __init__(self, name, tricks=None):
super().__init__(name)
self.tricks = list(tricks or [])
def speak(self):
return "Woof"
for animal in (Animal("Generic"), Dog("Rex")):
print(animal.name, animal.speak())
# Generic ...
# Rex Woof
print(Dog.__mro__) # (<class '__main__.Dog'>, <class '__main__.Animal'>, <class 'object'>)Dog does not define name itself. It gets it because Dog.__init__ calls super().__init__(name), which runs the Animal initializer on the same object. Dog overrides speak(), so Dog("Rex").speak() returns "Woof" instead of "...".
How Python finds a method
When you write obj.method(), Python looks for method in the object's own class first. If it is not there, Python checks the parent, then the parent's parent, and so on up to object. The first match wins. The order of this search is stored in __mro__, the method resolution order. The next chapter covers it in detail.
Overriding versus extending
An override can replace the parent's method completely, as Dog.speak does. It can also extend the parent's method by calling it and adding to the result:
class Animal:
def __init__(self, name):
self.name = name
def describe(self):
return f"{self.name} is an animal"
class Dog(Animal):
def describe(self):
return super().describe() + " and a dog"
print(Dog("Rex").describe()) # Rex is an animal and a dogExtending keeps the parent's logic in one place. If Animal.describe changes, Dog picks up the change.
Checking types in a hierarchy
Two built-in functions answer questions about hierarchies:
class Animal: ...
class Dog(Animal): ...
rex = Dog()
print(isinstance(rex, Dog)) # True
print(isinstance(rex, Animal)) # True: a Dog is an Animal
print(issubclass(Dog, Animal)) # True
print(isinstance(Animal(), Dog)) # False: the reverse does not holdPrefer isinstance over type(x) == Dog. The type comparison rejects subclasses, which breaks the substitution that inheritance is meant to allow.
Common errors
- Forgetting
super().__init__(). If a subclass defines__init__and does not call the parent's, the parent's attributes are never set. You then get anAttributeErrorsuch as'Dog' object has no attribute 'name'when you use them. - Changing a method's meaning. Code that works with an
Animalshould keep working when given aDog. An override that returns a different type or rejects valid arguments breaks that. - Using inheritance for "has-a". A
Caris not anEngine. Hold an engine as an attribute instead. A later chapter compares the two designs. - Deep hierarchies. Each level adds places where a method may be defined. Keep hierarchies shallow so readers can predict which code runs.
Exercise
Given class Animal with __init__(self, name) and class Cat(Animal) that defines its own __init__(self, name, indoor) but never calls super().__init__(name), what happens when you run Cat("Tom", True).name, and how do you fix it?
Show answer
It raises AttributeError: 'Cat' object has no attribute 'name', because Animal.__init__ never ran and so self.name was never set. Fix it by calling super().__init__(name) as the first line of Cat.__init__, then setting self.indoor = indoor.
Exercise
What do isinstance(Dog("Rex"), Animal) and type(Dog("Rex")) == Animal return, and why do they differ?
Show answer
The first returns True because isinstance accepts instances of subclasses. The second returns False because type(...) gives exactly Dog, which is not equal to Animal.