Python Classes and Objects · Lesson 85 of 149

Python Inheritance

What you will learn

  • What inheritance is and the is-a test
  • How to define a subclass
  • Overriding methods and class attributes
  • Calling the parent with super(), and why it matters in __init__
  • isinstance and issubclass
  • Subclassing built-in types such as list and dict

1. The idea: reuse by inheriting

Often one kind of thing is a special case of another. A dog is an animal. A manager is an employee. A square is a shape. Inheritance lets a new class take over everything from an existing class and then add or change only what is different.

Word Meaning
parent class (also base class, superclass) the class being inherited from
child class (also subclass, derived class) the new class that inherits

A quick test before using inheritance: say "a Dog is an Animal" aloud. If it sounds right, inheritance probably fits. "A Car is an Engine" is wrong (a car has an engine; see lesson 13.9).

2. Defining a subclass

Put the parent's name in brackets after the class name:

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return "..."

    def describe(self):
        return f"{self.name} says {self.speak()}"

class Dog(Animal):
    def speak(self):
        return "Woof"

class Cat(Animal):
    def speak(self):
        return "Meow"

class Fish(Animal):
    pass

for a in [Dog("Rex"), Cat("Tom"), Fish("Nemo"), Animal("Generic")]:
    print(a.describe())
Rex says Woof
Tom says Meow
Nemo says ...
Generic says ...

Notice what each subclass did not have to write:

  • Dog("Rex") works with no __init__ in Dog: the parent's __init__ is inherited and sets name.
  • describe is inherited by all three. It calls self.speak(), and Python picks the version belonging to the object's own class.
  • Fish has no body at all (pass), and still works: it uses everything from Animal, including the default speak.
Quick check: which `speak` does `Fish("Nemo").describe()` use?

Animal.speak, because Fish does not define its own, so Python finds the parent's version.

3. Overriding

When a subclass defines a method with the same name as one in the parent, the subclass's version replaces it for that class. This is called overriding:

print(Animal.speak is Dog.speak)
print(Fish.speak is Animal.speak)
False
True

Dog has its own speak. Fish has none, so Fish.speak is the parent's function. Python looks for a method in this order: the object's class first, then the parent, then the parent's parent, up to object. This chain is the method resolution order (MRO):

print([c.__name__ for c in Dog.__mro__])
['Dog', 'Animal', 'object']

Every class eventually inherits from object, the base of everything in Python.

4. Calling the parent: super()

Often you want to extend the parent's behaviour, not replace it. super() gives you the parent's version to call:

class Bird(Animal):
    def __init__(self, name, can_fly=True):
        super().__init__(name)
        self.can_fly = can_fly

    def speak(self):
        return "Tweet"

b = Bird("Tweety")
print(b.name, b.can_fly)
print(b.describe())
print(vars(b))
Tweety True
Tweety says Tweet
{'name': 'Tweety', 'can_fly': True}

super().__init__(name) runs Animal.__init__, which sets self.name. Then Bird adds its own attribute, can_fly. The same works for any method:

class Puppy(Dog):
    def speak(self):
        return super().speak() + " (squeaky)"

print(Puppy("Bit").describe())
Bit says Woof (squeaky)

The classic mistake: forgetting super().init

If a subclass defines its own __init__, the parent's __init__ is not run automatically. The parent's attributes never get created:

class BadBird(Animal):
    def __init__(self, name, can_fly=True):
        self.can_fly = can_fly

bb = BadBird("x")
bb.describe()
AttributeError: 'BadBird' object has no attribute 'name'

BadBird.__init__ took the name but never stored it. Rule: when you write __init__ in a subclass, call super().__init__(...) first (almost always).

The usual pattern in a subclass __init__:

  1. call super().__init__(...) with what the parent needs;
  2. then set the new attributes.

5. Changing class attributes

A subclass can override a class attribute (lesson 13.3), and the parent's methods will see the new value, if they look it up through self:

class Vehicle:
    wheels = 4

    def __init__(self, brand):
        self.brand = brand

    def info(self):
        return f"{self.brand} with {self.wheels} wheels"

class Bike(Vehicle):
    wheels = 2

class Car(Vehicle):
    def __init__(self, brand, doors=4):
        super().__init__(brand)
        self.doors = doors

    def info(self):
        return super().info() + f", {self.doors} doors"

print(Bike("BMX").info())
print(Car("Fiat").info())
print(Car("Mini", 2).info())
BMX with 2 wheels
Fiat with 4 wheels, 4 doors
Mini with 4 wheels, 2 doors

Bike changed only the number of wheels and reused everything else. Car extended info by calling the parent's version with super(), and adding the doors.

6. Testing types: isinstance and issubclass

d = Dog("Rex")
print(isinstance(d, Dog), isinstance(d, Animal), isinstance(d, Cat))
print(issubclass(Dog, Animal), issubclass(Animal, Dog), issubclass(Dog, object))
print(type(d) is Dog, type(d) is Animal)
True True False
True False True
True False
  • isinstance(obj, Class) is true if the object belongs to the class or any subclass. A Dog is an Animal.
  • issubclass(A, B) asks the same about two classes.
  • type(obj) is Class asks for the exact class and ignores inheritance.

Prefer isinstance in tests, because it respects inheritance (lesson 2.2). Reserve type(obj) is X for the rare case where you really need the exact class. Some surprising results of this rule: isinstance(True, int) is True, because bool is a subclass of int.

7. Subclassing built-in types

You can inherit from built-in classes, and add or change behaviour:

class MyList(list):
    def second(self):
        return self[1]

ml = MyList([1, 2, 3])
ml.append(4)
print(ml, ml.second(), len(ml))
print(isinstance(ml, list), type(ml).__name__)

class MyDict(dict):
    def __missing__(self, key):
        return f"<{key}>"

md = MyDict(a=1)
print(md["a"], md["zzz"])
[1, 2, 3, 4] 2 4
True MyList
1 <zzz>

MyList is a real list that has one extra method. MyDict defines the special method __missing__, which a dictionary calls when a key is not found, so a missing key gives a placeholder, not a KeyError. (Special methods are lesson 13.7.)

For a larger change, composition (lesson 13.9) or collections.UserList and UserDict can be safer, because some methods of the built-in types do not call your overrides.

8. A base class that expects overrides

A parent can provide a method that subclasses must write, and raise NotImplementedError if they forget:

class Shape:
    def area(self):
        raise NotImplementedError("subclasses must implement area")

    def describe(self):
        return f"{type(self).__name__} with area {self.area():.1f}"

class Square(Shape):
    def __init__(self, s):
        self.s = s

    def area(self):
        return self.s ** 2

class Circle(Shape):
    def __init__(self, r):
        self.r = r

    def area(self):
        return 3.14159 * self.r ** 2

print(Square(2).describe())
print(Circle(1).describe())
Shape().describe()
Square with area 4.0
Circle with area 3.1
NotImplementedError: subclasses must implement area

describe is written once in Shape, and works for every subclass, because each one supplies its own area. This is the template idea. Lesson 13.10 shows a stronger way to enforce it, with abstract base classes.

9. When not to inherit

Inheritance is easy to overuse. Warning signs:

  • the "is-a" sentence does not sound right (a Stack is not a list just because it uses one inside);
  • the subclass removes or disables things from the parent;
  • the hierarchy is deep (more than two or three levels);
  • you only want to reuse some code, not to create a kind-of relationship.

In those cases, make the object hold another object and use it: composition (lesson 13.9). A good motto: prefer composition, use inheritance for true "is-a" relationships.

Worked example: employees and managers

A company has employees with a name and a salary, and managers who also get a bonus. Compute the pay of each and of the whole team.

class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def pay(self):
        return self.salary

    def describe(self):
        return f"{self.name} ({type(self).__name__}) earns {self.pay()}"


class Manager(Employee):
    def __init__(self, name, salary, bonus):
        super().__init__(name, salary)
        self.bonus = bonus

    def pay(self):
        return super().pay() + self.bonus


class Intern(Employee):
    def pay(self):
        return super().pay() * 0.5


team = [Employee("Rina", 100), Manager("Sam", 200, 50), Intern("Lee", 60)]
for person in team:
    print(person.describe())

print(sum(p.pay() for p in team))
print([p.name for p in team if isinstance(p, Manager)])
print([p.name for p in team if isinstance(p, Employee)])
Rina (Employee) earns 100
Sam (Manager) earns 250
Lee (Intern) earns 30.0
380.0
['Sam']
['Rina', 'Sam', 'Lee']
Class What it adds or changes
Employee name, salary, pay, describe
Manager a bonus; extends pay with super().pay() + self.bonus
Intern overrides pay to give half (and uses super().pay() to get the base salary)

describe is written once, and shows the right class name and pay for each, because it calls self.pay() and type(self).__name__. Every Manager and Intern is an Employee, so isinstance(p, Employee) is true for all three. The names and numbers are made up.

Common mistakes

  • Forgetting super().__init__(...) in a subclass __init__, so the parent's attributes are missing.
  • Using inheritance when the relationship is "has-a" (use composition instead).
  • Overriding a method with a different meaning, so that code expecting the parent breaks.
  • Hard-coding the parent's name instead of using super().
  • Using type(x) is Y where isinstance(x, Y) was meant.
  • Creating deep hierarchies that are hard to follow.

Key takeaways

  • class Child(Parent): gives Child all the attributes and methods of Parent; use inheritance for true "is-a" relationships.
  • A method with the same name in the child overrides the parent's; Python looks in the object's class first, then up the chain (MRO).
  • super() reaches the parent's version; call super().__init__(...) first in a subclass __init__.
  • isinstance(obj, Class) includes subclasses; issubclass compares classes; type(obj) is Class is exact.
  • Built-in types can be subclassed; prefer composition when the relationship is "has-a" or the hierarchy grows deep.

Practice

1. Write a class Cat that inherits from Animal and overrides speak to return "Meow".

Show answer
class Cat(Animal):
    def speak(self):
        return "Meow"

2. What does super().__init__(name) do in a subclass?

Show answer

It runs the parent class's __init__ with the given arguments, so that the parent's attributes are set up.

3. What error appears if a subclass writes __init__ without calling the parent's and a method then uses self.name?

Show answer

AttributeError: 'BadBird' object has no attribute 'name': the attribute was never created.

4. Is a Puppy(Dog) object an instance of Animal when Dog inherits from Animal?

Show answer

Yes. isinstance is true for the class itself and every class above it in the inheritance chain.

5. Which sentence tells you inheritance fits: "a Car is an Engine" or "a Dog is an Animal"?

Show answer

"A Dog is an Animal." A car has an engine, which suggests composition rather than inheritance.

6. What does Fish.speak is Animal.speak show when Fish has no speak?

Show answer

True: Fish has no method of its own, so it uses the parent's one.