Skip to content
Tutorials Center
My learning

Topics

Lesson 76 of 149 ยท Object-Oriented Programming

Inheritance

Learn Python inheritance step by step - create subclasses, override methods, extend them with super(), check types with isinstance, and understand the MRO.

Inheritance lets you create a new class from an existing one. The new class, called a subclass (or child class), automatically gets every attribute and method of the original base class (or parent class). You then add what's new and change what's different.

Inheritance models an "is a" relationship: a savings account is a bank account, a circle is a shape. Used well, it removes repeated code and lets different classes share one interface. Used carelessly, it ties classes together too tightly, so this lesson also covers when to prefer other designs.

Creating a subclass

Put the base class in parentheses after the new class name. With nothing else inside, the subclass behaves exactly like its parent:

Python A first subclass

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Dog defines nothing, yet rex.introduce() works. When you look up an attribute on an object, Python checks the object itself, then its class, then that class's parents, and so on up the chain. Every class you write ultimately inherits from the built-in object, which is where default behavior such as __repr__ comes from.

isinstance(obj, cls) is true for the object's own class and any of its ancestors. That's usually what you want: code that expects an Animal should accept a Dog. issubclass() asks the same question about two classes.

Overriding methods

To change behavior, define a method with the same name in the subclass. The subclass version overrides the inherited one:

Python Overriding a method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look closely: introduce() lives only in Animal, but it calls self.speak(). Because self is a Dog or a Cat, Python finds the subclass's speak. This is called polymorphism: one piece of code, pet.introduce(), behaves correctly for many types. The loop doesn't need any if statements about which kind of animal it has.

Extending with super()

Often you don't want to replace the parent's method, only to add to it. super() gives you access to the parent class's version, so you can call it and then do your extra work. The most common place is __init__:

Python super() in __init__

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

If SavingsAccount.__init__ forgot to call super().__init__(), the object would have a rate but no owner or balance, and summary() would crash with an AttributeError. A good rule: whenever a subclass defines __init__, it should call super().__init__(...) so the parent can set up its part.

summary() shows the same idea for ordinary methods: reuse the parent's result and decorate it, instead of copying its code.

Tip: super() with no arguments works inside any method of a class. You may see super(SavingsAccount, self) in older code; it means the same thing and is no longer needed.

Checking for a parent method you meant to override

A subtle bug with overriding is a typo in the method name. If Dog defines speek() instead of speak(), nothing fails: Dog simply gains a new method, and the parent's speak() keeps running. Python 3.12 added the @override decorator in the typing module to catch this. Put it above a method that's meant to replace a parent's method, and a type checker such as mypy reports an error if no parent method with that name exists:

Python
from typing import override

class Dog(Animal):
    @override
    def speak(self) -> str:
        return f"{self.name} barks."

At runtime @override does nothing visible; it's a promise that tools check for you.

Inheritance chains

A subclass can itself have subclasses. Each level adds or changes a little:

Python A three-level chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The class attribute wheels is looked up the same way as methods: ElectricCar doesn't define it, so Python finds 4 on Car. The last line prints the method resolution order (MRO), the exact list of classes Python searches, in order, for any attribute.

Multiple inheritance and the MRO

Python allows a class to inherit from more than one base class. This is mostly used for small mixins: classes that add one focused ability and aren't meant to be used alone.

Python A mixin

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

With several parents, the MRO decides who wins when two of them define the same name. Python builds it with an algorithm called C3 linearization, which guarantees two things: a class always comes before its parents, and parents keep the left-to-right order you listed. So for WebProduct(JsonMixin, GreetMixin, Product), Python searches WebProduct, JsonMixin, GreetMixin, Product, then object.

This is also why super() means "the next class in the MRO", not simply "my parent". In a multiple-inheritance hierarchy, each super() call hands off to the next class in that list, so every class gets its turn exactly once, as long as they all call super().

Warning: Deep or tangled multiple inheritance is hard to follow. Keep mixins small, give them no __init__ if you can, and avoid two parents that both define the same method unless you understand the MRO for that class.

When not to use inheritance

Inheritance is powerful, but it isn't the only way to reuse code. Ask whether the relationship is really "is a". If it's "has a", use composition: store another object as an attribute.

Python
class Engine:
    def start(self) -> str:
        return "engine running"


class Car:
    def __init__(self) -> None:
        self.engine = Engine()   # a car HAS an engine

    def start(self) -> str:
        return self.engine.start()

A Car is not a kind of Engine, so class Car(Engine) would be misleading, and every engine method would leak into the car's interface. Composition keeps each class small and lets you swap parts later. Many Python programs also rely on duck typing instead of shared base classes: if an object has the methods you need, you use it. You'll explore that idea in Abstract Classes and Protocols.

You've already met an excellent use of inheritance, by the way: Custom Exceptions subclass Exception so that except clauses can catch whole families of errors.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given class Dog(Animal), what does isinstance(Dog("Rex"), Animal) return?

    isinstance returns True for the object's class and all of its ancestors.
  2. 2. A subclass defines its own __init__. What usually goes wrong if it forgets super().__init__(...)?

    Python only runs the subclass's __init__. The parent's setup runs only if you call it with super().__init__(...).
  3. 3. In class C(A, B), both A and B define hello(). Which one does C().hello() call?

    The MRO keeps the left-to-right order of the base classes, so Python finds hello on A first.
  4. 4. Which design fits "a playlist has many songs"?

    "Has a" relationships call for composition. A playlist is not a kind of song.
  5. 5. What does super() refer to in a class that uses multiple inheritance?

    super() follows the method resolution order, which lets every class in a hierarchy run its part once.

Summary

  • A subclass inherits all attributes and methods of its base class: class Dog(Animal):.
  • Override a method by defining one with the same name; parent code calling self.method() uses the subclass version (polymorphism).
  • Use super() to call the parent's version, especially super().__init__(...) in a subclass's __init__.
  • isinstance() and issubclass() include ancestor classes.
  • The MRO (Class.__mro__) is the order Python searches for attributes; with multiple inheritance it keeps left-to-right order, and super() follows it.
  • Prefer small mixins for multiple inheritance, and composition when the relationship is "has a" rather than "is a".

Next: Special (Dunder) Methods, where you'll teach your classes to work with print(), ==, len(), + and more.