Inheritance lets you create a new class from one that already exists. The new class (the subclass) receives all the attributes and methods of the original (the superclass) and can add its own or change the ones that do not suit it.
The "is a" relationship
Inheritance is used when a class is a kind of another: a dog is an animal, a car is a vehicle, a student is a person. If the sentence sounds odd ("a car is an engine"), it is probably not inheritance.
A subclass
class Animal:
def __init__(self, name):
self.name = name
def eat(self):
print(f"{self.name} is eating")
class Dog(Animal): # Dog inherits from Animal
def bark(self):
print("Woof!")
rex = Dog("Rex")
rex.eat() # Rex is eating (inherited)
rex.bark() # Woof! (its own)
The base class goes in parentheses after the name of the new one. Dog defines neither __init__ nor eat: it uses them as they are from Animal.
super(): using the superclass
If the subclass needs its own constructor, it must call the superclass one with super().__init__(...) so the inherited attributes are initialized:
class Cat(Animal):
def __init__(self, name, lives):
super().__init__(name) # initializes self.name
self.lives = lives
kitty = Cat("Kitty", 7)
print(kitty.name, kitty.lives) # Kitty 7
Overriding a method
A subclass can redefine a method with the same name. Its own will be used instead of the inherited one:
class Cow(Animal):
def eat(self):
print(f"{self.name} grazes calmly")
Cow("Daisy").eat() # Daisy grazes calmly
And if you want to extend the behaviour instead of replacing it, call super() as well:
class Pig(Animal):
def eat(self):
super().eat()
print("And again!")
What belongs to whom: isinstance and issubclass
print(isinstance(rex, Dog)) # True
print(isinstance(rex, Animal)) # True (a dog is an animal)
print(isinstance(rex, Cat)) # False
print(issubclass(Dog, Animal)) # True
isinstance is used to tell types apart when you have a list with objects of several subclasses:
animals = [Dog("Rex"), Cat("Kitty", 7), Dog("Fido")]
for a in animals:
if isinstance(a, Dog):
a.bark()
Multilevel inheritance
A subclass can have its own subclasses (Puppy(Dog)), and it inherits from the whole chain. The order in which Python looks for a method is: first the class itself, then its superclass, then that one's, and so on.
Practice with Inheritance of objects, the exercise about the Person, Student and Teacher classes and, to see how a subclass adjusts the constructor values, Photo book class.