Inheritance in Python

Building related classes in Python starts with deciding what behavior the new class should share. Inheritance lets a new class, called a subclass, reuse behavior from an existing class.

This article shows how to define a subclass and extend an overridden method with super().

TL;DR

Inheritance lets a Python subclass reuse behavior from a base class, replace selected methods, or extend them with super().

  • Write the base class in parentheses after the subclass name, as in class Admin(Account).
  • Call super().__init__() when the child initializer adds state that the parent must also set.
  • Check method lookup with ClassName.__mro__ when multiple bases provide the same method.

What Is Inheritance in Python?

A class can derive from another class by naming it in parentheses. The named class is the base, and the new class is its subclass. I kept the first working example to one base and one child because that shows lookup before a second base adds ordering questions.

Inheritance and Memory

Each Admin object stores its own name and permissions on the instance. Python resolves describe() on the class hierarchy, so the method is reused rather than copied into that object’s state.

Benefits of Inheritance

A shared implementation keeps related types consistent. If Account provides a status check and both Admin and Guest inherit it, one correction serves both roles instead of maintaining duplicated versions. Test the shared method and each override because an inherited change can affect several concrete classes.

An Admin is a specific kind of Account, so a function written to accept an Account can also receive an Admin value.

FormShapeExampleUse
SingleOne subclass inherits from one baseAdmin(Account)Add one role to shared account behavior
MultilevelA subclass derives from a subclassTeamLead(Admin)Specialize a class that already extends a base
HierarchicalSeveral subclasses inherit a shared baseAdmin(Account), Guest(Account)Give sibling roles common operations
MultipleOne class names several basesReport(Admin, Exporter)Combine independent behaviors with a deliberate MRO
HybridA hierarchy combines single, multilevel, or multiple inheritanceA diamond-shaped family of basesModel a graph with more than one inheritance form
Shapes class with Triangle, Circle, and Square subclasses, plus Equilateral Triangle
The diagram shows Shapes with three direct subclasses and Equilateral Triangle one level below Triangle, not multiple inheritance.

With TeamLead(Admin), Python searches TeamLead, Admin, and then Account before object. This nested inheritance lets a TeamLead object use a method supplied by either ancestor, unless TeamLead defines its own version.

MemberWhat inheritance meansWhen a child changes it
MethodThe base implementation can be called on a child instanceA same-named child method overrides it
PropertyThe child can read the base property through attribute accessA same-named property can provide child-specific behavior
Class attributeThe value can be read through the child classAn instance assignment shadows the class value

A property exposes a method through attribute-style access, so callers read account.balance instead of calling account.balance(). A child can inherit that access or replace the property to change its calculation. With @property and @balance.setter, the class can also validate account.balance = value, and a replacement property should preserve the setter when callers rely on assignment.

A mutable class attribute is shared by instances until an instance assigns its own value. Put per-object lists in __init__() when one object’s changes should leave the others alone, because Python does not copy that list for each object.

An empty subclass can contain pass and inherit the available behavior. That creates a distinct type for checks or later specialization without copying the base implementation, and the child can add methods later if its role grows.

How to Build a Python Subclass Step by Step

Put the base class in the subclass declaration, then add only the state or behavior that differs. A child without its own __init__() inherits the parent’s initializer.

Step 1: Define the base class

Account stores a name through self and defines describe() for an Admin instance to reuse.

Step 2: Add a subclass initializer

Admin(Account) accepts the name needed by Account plus a permission list. Its initializer forwards the name to Account, then stores the list on the Admin instance.

Step 3: Override the description method

Admin defines describe() because its output includes permissions as well as the account name. The call to super().describe() keeps the base description before Admin adds its own detail.

Step 4: Run the complete example

I ran the complete example with python3 inheritance_walkthrough.py. The output shows the inherited name, the added permissions, and both relationship checks in their returned values.

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

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


class Admin(Account):
    def __init__(self, name, permissions):
        super().__init__(name)
        self.permissions = permissions

    def describe(self):
        return f"{super().describe()} | access: {', '.join(self.permissions)}"


admin = Admin("Mira", ["reports", "users"])
print(admin.describe())
print("isinstance:", isinstance(admin, Account))
print("issubclass:", issubclass(Admin, Account))

Output

Member: Mira | access: reports, users
isinstance: True
issubclass: True
Python subclass inherits a description method and extends it with permissions
The Admin object keeps its inherited name and adds its own permission list.

The first output line starts with Member from Account.describe() and adds the access list from Admin.describe(). The returned string shows the base and child implementations in one result.

Use isinstance() with an object and issubclass() with class objects. The first accepts an instance of Admin, while the second checks Admin’s class relationship before creating an object. Both include indirect subclasses.

Inheritance Edge Cases and Design Choices

I left out super().__init__() and ran python3 missing_parent_init.py. Draft.show_title() raised the error below because the child initializer never set the title that the inherited method reads. Call super().__init__(title) before assigning child-specific fields.

class Document:
    def __init__(self, title):
        self.title = title

    def show_title(self):
        print(self.title)


class Draft(Document):
    def __init__(self, body):
        self.body = body


try:
    Draft("Proposal").show_title()
except AttributeError as error:
    print(f"{type(error).__name__}: {error}")

Output

AttributeError: 'Draft' object has no attribute 'title'
Python AttributeError when a subclass skips the parent initializer
Command output in a terminal window.

I tested the diamond below to answer why Right runs after Left calls super() even though Left only names Root.

class Root:
    def action(self):
        return ["Root"]


class Left(Root):
    def action(self):
        return ["Left", *super().action()]


class Right(Root):
    def action(self):
        return ["Right", *super().action()]


class Bottom(Left, Right):
    pass


print("MRO:", " -> ".join(cls.__name__ for cls in Bottom.__mro__))
print("calls:", " -> ".join(Bottom().action()))

Output

MRO: Bottom -> Left -> Right -> Root -> object
calls: Left -> Right -> Root
Python cooperative super calls through the method resolution order
Bottom’s class order and the resulting method calls appear in the terminal.

The printed order puts Bottom before Left and Right, then reaches the shared Root once. I printed Bottom.__mro__ because the calls alone do not show why Left reaches Right without naming it.

Each implementation must call super() for a cooperative chain to continue. If one method returns without delegating, later classes do not participate in that call.

Protected Attributes

A leading underscore marks an internal name by convention, not enforced protected access. A double-leading underscore triggers name mangling with the defining class name to reduce accidental subclass collisions. Account’s __token becomes _Account__token, but the transformed attribute remains accessible and is not a way to hide sensitive values.

CaseWhat you seeWhat to do
A subclass changes a method’s parametersA call through the base interface can failKeep the override signature compatible
A mutable value lives on the classSeveral instances observe the same valueAssign per-object state in __init__()
A class uses a collaboratorA Report owns a Formatter it callsStore the collaborator as an attribute
Report needs formatting behaviorReport holds a Formatter and delegates the callUse composition for this has-a relationship
Subclasses must supply named operationsAn abstract class cannot be instantiated until they are implementedUse abc.ABC and @abstractmethod, or typing.Protocol for a structural type contract

Conclusion

The Python class tutorial is the first-party reference for inheritance syntax and attribute lookup.

Use the Python class tutorial for inheritance rules. The abc module and typing.Protocol docs cover required methods and structural typing. AskPython also has focused guides to super(), multiple inheritance, and class constructors.

FAQ

These answers cover follow-up questions about inherited initialization and calling another implementation.

Does a child class inherit the parent initializer?

Yes. If the child does not define __init__(), Python finds the inherited initializer through the class lookup order.

Can super() call a method other than __init__()?

Yes. Use super().method_name() to continue lookup for that method after the current class in the instance’s MRO.

Safa Mulani
Safa Mulani

An enthusiast in every forthcoming wonders!

Articles: 189