Python Tutorial › Object-Oriented Python › Inheritance

Python Inheritance

IntermediateLesson 32 of 4711 min read8 runnable examples

Inheritance lets a new class reuse and extend an existing one. The child class gets all the parent’s attributes and methods, and can add its own or change how some of them behave. Page Object frameworks use this to share common page code in a BasePage.

Advertisement
In this lesson
  • Create a child class
  • Extend __init__ with super()
  • Override methods
  • Multiple inheritance and the MRO

A parent and a child

Put the parent class in brackets after the child’s name. The child inherits everything from the parent.

Python
class Vehicle:    def __init__(self, brand):        self.brand = brand     def start(self):        return f"{self.brand} engine started" class Car(Vehicle):        # Car inherits from Vehicle    pass c = Car("Tata")print(c.start())print(isinstance(c, Car), isinstance(c, Vehicle))
Output
Tata engine started
True True

Add attributes with super()

To add new attributes, define __init__ in the child and call the parent’s __init__ with super(), so the parent’s setup still happens.

Python
class Vehicle:    def __init__(self, brand):        self.brand = brand class Car(Vehicle):    def __init__(self, brand, seats):        super().__init__(brand)     # let Vehicle set brand        self.seats = seats          # then add Car's own data c = Car("Mahindra", 7)print(c.brand, c.seats)
Output
Mahindra 7
Watch out

If the child defines __init__ and forgets super().__init__(...), the parent’s attributes are never set and you get AttributeError later.

Override methods

A method with the same name in the child replaces the parent’s version. Call super().method() to reuse the parent’s code inside the new one.

Python
class Employee:    def __init__(self, name, salary):        self.name = name        self.salary = salary     def annual_pay(self):        return self.salary * 12     def describe(self):        return f"{self.name} earns {self.annual_pay()} a year" class Manager(Employee):    def __init__(self, name, salary, bonus):        super().__init__(name, salary)        self.bonus = bonus     def annual_pay(self):                     # override        return super().annual_pay() + self.bonus staff = [Employee("Asha", 50000), Manager("Ravi", 80000, 100000)]for person in staff:    print(person.describe())
Output
Asha earns 600000 a year
Ravi earns 1060000 a year

describe() is defined only in Employee, yet for a Manager it calls the overridden annual_pay(). Python always looks up the method on the actual object.

A real example: page objects

Python
class BasePage:    url = "/"     def __init__(self, base_url):        self.base_url = base_url     def open(self):        return f"GET {self.base_url}{self.url}" class LoginPage(BasePage):    url = "/login"     def login(self, user):        return f"{self.open()} -> sign in as {user}" class CartPage(BasePage):    url = "/cart" print(LoginPage("https://shop.test").login("asha"))print(CartPage("https://shop.test").open())
Output
GET https://shop.test/login -> sign in as asha
GET https://shop.test/cart

Multilevel inheritance

A child can itself be a parent:

Python
class Animal:    def breathe(self):        return "breathing" class Mammal(Animal):    def feed(self):        return "feeding milk" class Dog(Mammal):    def bark(self):        return "woof" d = Dog()print(d.breathe(), "|", d.feed(), "|", d.bark())
Output
breathing | feeding milk | woof

Multiple inheritance and the MRO

A class can inherit from several parents. When two parents define the same method, Python follows the method resolution order (MRO): the child first, then the parents from left to right.

Python
class Flyer:    def move(self):        return "flying" class Swimmer:    def move(self):        return "swimming" class Duck(Flyer, Swimmer):    pass print(Duck().move())print([cls.__name__ for cls in Duck.__mro__])
Output
flying
['Duck', 'Flyer', 'Swimmer', 'object']
Tip

Multiple inheritance is mostly used for small “mixin” classes that add one feature, such as logging. Keep hierarchies shallow.

Checking relationships

Python
class A: passclass B(A): pass print(issubclass(B, A), issubclass(A, B))print(isinstance(B(), A))
Output
True False
True

Abstract base classes

An abstract class defines methods that every child must implement. You cannot create an object from it directly.

Python
from abc import ABC, abstractmethod class Shape(ABC):    @abstractmethod    def area(self):        ... class Square(Shape):    def __init__(self, side):        self.side = side    def area(self):        return self.side ** 2 print(Square(4).area())Shape()
Output
16
Traceback (most recent call last):
  File "main.py", line 15, in <module>
    Shape()
    ~~~~~^^
TypeError: Can't instantiate abstract class Shape without an implementation for abstract method 'area'

Check your understanding

Predict the output

class A:    def hello(self):        return "A"class B(A):    def hello(self):        return "B+" + super().hello()class C(B):    pass print(C().hello())

Quick quiz

1. How do you call the parent’s __init__ from a child?

2. What is method overriding?

3. For class D(B, C), where is a method looked up after D?

Exercise: savings account

Create SavingsAccount that inherits from Account, adds an interest_rate, and has an add_interest() method.

Input
SavingsAccount("Meena", 1000, 0.05)
Expected output
Meena 1050.0
Hint 1

Call super().__init__(owner, balance) first.

Program Practice

48 Python OOP Programs

Every program has a step-by-step explanation, colour-coded code and its real output.

Start practising →
Related sets:All practice sets

Python inheritance FAQ

What does super() do in Python?

super() gives access to methods of the parent class (strictly, the next class in the MRO), most often to call the parent’s __init__ or an overridden method.

Does Python support multiple inheritance?

Yes. A class can list several parents. Python resolves name clashes with the method resolution order (C3 linearisation), which you can inspect with ClassName.__mro__.

What is the difference between inheritance and composition?

Inheritance models “is a” (a Manager is an Employee). Composition models “has a” (a Car has an Engine) by storing another object as an attribute. Prefer composition when the relationship is not truly “is a”.

Leave a Comment