Python Inheritance
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.
- 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.
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))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.
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)Mahindra 7
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.
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())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
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())GET https://shop.test/login -> sign in as asha GET https://shop.test/cart
Multilevel inheritance
A child can itself be a parent:
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())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.
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__])flying ['Duck', 'Flyer', 'Swimmer', 'object']
Multiple inheritance is mostly used for small “mixin” classes that add one feature, such as logging. Keep hierarchies shallow.
Checking relationships
class A: passclass B(A): pass print(issubclass(B, A), issubclass(A, B))print(isinstance(B(), A))True False True
Abstract base classes
An abstract class defines methods that every child must implement. You cannot create an object from it directly.
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()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())B+A
C has no hello, so Python finds it in B. B.hello calls super().hello(), which is A‘s version.
Quick quiz
1. How do you call the parent’s __init__ from a child?
super() returns a proxy to the next class in the MRO.
2. What is method overriding?
The child’s version replaces the parent’s for child objects.
3. For class D(B, C), where is a method looked up after D?
The MRO goes left to right through the parents.
Exercise: savings account
Create SavingsAccount that inherits from Account, adds an interest_rate, and has an add_interest() method.
SavingsAccount("Meena", 1000, 0.05)Meena 1050.0
Hint 1
Call super().__init__(owner, balance) first.
class Account: def __init__(self, owner, balance=0): self.owner = owner self.balance = balance def deposit(self, amount): self.balance += amount class SavingsAccount(Account): def __init__(self, owner, balance, interest_rate): super().__init__(owner, balance) self.interest_rate = interest_rate def add_interest(self): self.deposit(self.balance * self.interest_rate) s = SavingsAccount("Meena", 1000, 0.05)s.add_interest()print(s.owner, s.balance)Meena 1050.0
The child reuses the parent’s setup and its deposit() method, adding only what is new: the rate and the interest calculation.
Program Practice
48 Python OOP Programs
Every program has a step-by-step explanation, colour-coded code and its real output.
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”.