Python OOP
Inheritance
Complete lesson for Inheritance using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.
Basics — Inheritance
Section: Python OOP. Reuse and extend classes with single, multilevel, hierarchical, and multiple inheritance; understand super(), MRO, and IS-A vs HAS-A.
What is inheritance?
- Inheritance lets a new class (child / subclass) reuse attributes and methods of an existing class (parent / base / superclass) and add or change behaviour.
- Syntax:
class Child(Parent):. A child **IS-A** parent:Dogis anAnimal. - Every new-style class ultimately inherits from
object(implicit in Python 3). - The child gets usable parent members, may add new ones, and may override inherited methods.
| Term | Also called | Meaning |
|---|---|---|
| Base class | Parent, superclass | Class being inherited from |
| Derived class | Child, subclass | Class that inherits |
super() | Cooperative parent call | Calls the next class in the MRO |
| Override | Replace method | Same name in child, new body |
| MRO | Method Resolution Order | Order Python searches for attributes |
| IS-A | Inheritance | Dog is an Animal |
| HAS-A | Composition | Car has an Engine |
class Animal:
def __init__(self, name: str) -> None:
self.name = name
def eat(self) -> None:
print(f"{self.name} is eating")
class Dog(Animal): # Dog IS-A Animal
def bark(self) -> None:
print(f"{self.name} is barking")
try:
d = Dog("Tommy")
d.eat() # inherited
d.bark() # own method
print("issubclass(Dog, Animal):", issubclass(Dog, Animal))
print("isinstance(d, Animal):", isinstance(d, Animal))
except Exception as e:
print("Error:", e) Why use inheritance?
- Reuse: write shared logic once in the parent.
- Extend: add specialised behaviour in children without editing the parent.
- Polymorphism: treat many child types through a shared parent interface.
- Model real “kind of” relationships (Manager is an Employee).
- Prefer composition when the relationship is “has a”, not “is a”.
Types of inheritance in Python
- Python supports single, multilevel, hierarchical, multiple, and hybrid inheritance with classes (no separate
interfacekeyword). - Multiple inheritance is allowed; the C3 linearisation (MRO) resolves method lookup.
| Type | Shape | Real-life example | Python |
|---|---|---|---|
| Single | A → B | Mobile → SmartPhone | class B(A) |
| Multilevel | A → B → C | Person → Employee → Manager | class C(B) where B(A) |
| Hierarchical | A → B, A → C | Shape → Circle, Rectangle | Many classes subclass one parent |
| Multiple | A, B → C | Flyer + Swimmer → Duck | class C(A, B) |
| Hybrid | Mix | TA is Student and Teacher-like mixin | Combine multilevel + multiple |
Types of inheritance in Python — with real-life examples
Python supports single, multilevel, hierarchical,
multiple, and hybrid inheritance with classes —
including multiple class parents (class Child(A, B)). Method lookup follows the
C3 MRO (Class.__mro__).
__mro__ - Single: one parent —
class SmartPhone(Mobile). - Multilevel: a chain —
Son(Father)whereFather(GrandFather). - Hierarchical: one parent, many children — Manager, Developer, Tester under
Employee. - Multiple / hybrid: allowed with classes — use
Class.__mro__to see lookup order.
Single inheritance
- One child class lists exactly one parent in the class header.
- Real life: a smartphone is a mobile phone that also browses the web.
class Mobile:
def __init__(self, brand: str) -> None:
self.brand = brand
def call(self, number: str) -> None:
print(f"{self.brand} calling {number}")
class SmartPhone(Mobile):
def browse(self, site: str) -> None:
print(f"{self.brand} opening {site}")
try:
phone = SmartPhone("Pixel")
phone.call("9876543210")
phone.browse("learncodeguru.com")
except Exception as e:
print("Error:", e) Multilevel inheritance
- A chain:
CinheritsB,BinheritsA.Csees members from both levels. - Keep chains short (two or three levels) so code stays readable.
class Person:
def __init__(self, name: str) -> None:
self.name = name
def intro(self) -> str:
return f"Person:{self.name}"
class Employee(Person):
def __init__(self, name: str, emp_id: int) -> None:
super().__init__(name)
self.emp_id = emp_id
def intro(self) -> str:
return f"{super().intro()}, id={self.emp_id}"
class Manager(Employee):
def __init__(self, name: str, emp_id: int, team: int) -> None:
super().__init__(name, emp_id)
self.team = team
def intro(self) -> str:
return f"{super().intro()}, team={self.team}"
try:
print(Manager("Asha", 101, 5).intro())
except Exception as e:
print("Error:", e) Hierarchical inheritance
- Several children share one parent — common in real projects.
- Real life: Manager, Developer, and Tester are all Employees.
class Employee:
def __init__(self, name: str) -> None:
self.name = name
def work(self) -> None:
print(f"{self.name} is working")
class Manager(Employee):
def meet(self) -> None:
print(f"{self.name} conducts a meeting")
class Developer(Employee):
def code(self) -> None:
print(f"{self.name} writes Python")
try:
Manager("Asha").work()
Manager("Asha").meet()
Developer("Ravi").work()
Developer("Ravi").code()
except Exception as e:
print("Error:", e) Multiple inheritance and mixins
- A class can list several parents:
class C(A, B). - Mixins are small parent classes that add one capability (logging, JSON export) without being a full domain base.
- Left-to-right order in the class header matters for the MRO.
class Camera:
def take_photo(self) -> None:
print("Photo clicked")
class MusicPlayer:
def play(self, song: str) -> None:
print(f"Playing {song}")
class SmartPhone(Camera, MusicPlayer):
def call(self, number: str) -> None:
print(f"Calling {number}")
try:
phone = SmartPhone()
phone.take_photo()
phone.play("Vande Mataram")
phone.call("100")
print("MRO:", [c.__name__ for c in SmartPhone.__mro__])
except Exception as e:
print("Error:", e) super() and constructor chaining
super()cooperates with the MRO so each class in a multiple-inheritance chain runs once.- Prefer
super().__init__(...)over hard-codingParent.__init__(self, ...). - Child
__init__should initialise the parent before using inherited state.
class Vehicle:
def __init__(self, number: str) -> None:
self.number = number
print("Vehicle init")
class Car(Vehicle):
def __init__(self, number: str, seats: int) -> None:
super().__init__(number)
self.seats = seats
print("Car init")
try:
c = Car("TS09AB1234", 5)
print(c.number, c.seats)
except Exception as e:
print("Error:", e) Method overriding
- Define a method with the same name in the child to replace parent behaviour.
- Call the parent version with
super().method(...)when you want to extend, not fully replace. - Attribute lookup uses the instance’s class MRO, so the child’s method wins for that object.
class Account:
def __init__(self, balance: float) -> None:
self.balance = balance
def withdraw(self, amount: float) -> bool:
if amount <= 0 or amount > self.balance:
return False
self.balance -= amount
return True
class CurrentAccount(Account):
def __init__(self, balance: float, overdraft: float) -> None:
super().__init__(balance)
self.overdraft = overdraft
def withdraw(self, amount: float) -> bool:
if amount <= 0 or amount > self.balance + self.overdraft:
return False
self.balance -= amount
return True
try:
c = CurrentAccount(5000, 2000)
print(c.withdraw(6500), c.balance)
except Exception as e:
print("Error:", e) IS-A vs HAS-A (composition)
- IS-A → inheritance. HAS-A → store another object as an attribute (composition).
- Prefer composition when you only need to reuse behaviour without exposing the full parent API.
class Engine:
def start(self) -> None:
print("Engine started")
class Car:
def __init__(self) -> None:
self.engine = Engine() # HAS-A Engine
def start(self) -> None:
self.engine.start()
try:
Car().start()
except Exception as e:
print("Error:", e) Advanced — Inheritance
Diamond problem and C3 MRO
- Diamond:
DinheritsBandC, both inheritA. WhichA/ method runs? - Python uses C3 linearisation. Inspect with
Class.__mro__orClass.mro(). - With cooperative
super(), each class in the diamond runs once in MRO order.
class A:
def ping(self) -> str:
return "A"
class B(A):
def ping(self) -> str:
return "B->" + super().ping()
class C(A):
def ping(self) -> str:
return "C->" + super().ping()
class D(B, C):
def ping(self) -> str:
return "D->" + super().ping()
try:
print(D().ping())
print([c.__name__ for c in D.__mro__])
except Exception as e:
print("Error:", e) Attribute lookup rules
- Instance attribute → class dict → parent classes in MRO → fail with
AttributeError. - Data descriptors on the class (e.g. properties) can intercept instance dict access.
- Name mangling (
__private) rewrites names to_Class__privateto reduce accidental clashes in subclasses.
class Base:
def __init__(self) -> None:
self.__token = "secret"
def show(self) -> None:
print(self.__token)
class Child(Base):
def __init__(self) -> None:
super().__init__()
self.__token = "child" # different mangled name
try:
c = Child()
c.show()
print(c.__dict__)
except Exception as e:
print("Error:", e) isinstance / issubclass and abstract bases
isinstance(obj, cls)is True forclsor any subclass (and registered virtual subclasses).issubclass(Sub, Base)checks the class relationship.- Collections ABCs (
MutableSequence,Mapping) let you test capabilities, not only concrete types.
from collections.abc import Sequence
try:
print(isinstance([1, 2], list))
print(isinstance([1, 2], Sequence))
print(issubclass(bool, int))
except Exception as e:
print("Error:", e) When inheritance hurts
- Subclassing built-ins incorrectly (e.g. extending
listfor a playlist) exposes unwanted methods. - Deep fragile base classes: a parent change breaks many children.
- Favour mixins that are orthogonal, or composition + delegation.
Slots and inheritance
- Classes with
__slots__save memory; subclasses must declare their own slots for new attributes. - Multiple inheritance with slots requires care — avoid unless you need the memory win.
Tricky Interview Points
Q1) What is inheritance in Python?
Answer A mechanism where a subclass reuses and extends a base class by listing parents in the class header, modelling an IS-A relationship.
Q2) What types of inheritance does Python support?
Answer Single, multilevel, hierarchical, multiple, and hybrid — all with classes. Multiple inheritance uses the C3 MRO.
Q3) What is the diamond problem and how does Python solve it?
Answer Ambiguity when two parents share a grandparent. Python’s C3 MRO linearises the graph so each class appears once; cooperative super() follows that order.
Q4) What does super() do?
Answer Returns a proxy that delegates to the next class in the MRO, enabling cooperative multiple inheritance instead of hard-coding a parent name.
Q5) How do you check inheritance relationships?
Answer isinstance(obj, Class) for objects; issubclass(Sub, Base) for classes; inspect Class.__mro__ for the full search order.
Q6) Are constructors inherited?
Answer __init__ is inherited like any method, but subclasses often override it and should call super().__init__ to initialise parents.
Q7) IS-A vs HAS-A?
Answer IS-A is inheritance (Car is a Vehicle). HAS-A is composition (Car has an Engine). Prefer HAS-A unless the subclass truly specialises the parent.
Q8) What is a mixin?
Answer A small parent class that adds a capability (e.g. JSON serialisation) intended to be combined via multiple inheritance, not used alone as a domain base.
Q9) Can you inherit from built-in types?
Answer Yes (list, dict, Exception, etc.). Prefer collections.UserList/UserDict when you need to customise behaviour safely, or use composition.
Q10) What is method overriding?
Answer Redefining a parent method in the child with the same name so attribute lookup finds the child’s version for that instance.
Q11) How does name mangling interact with inheritance?
Answer Names like __attr become _ClassName__attr, so parent and child “private” attributes do not collide.
Q12) Why prefer composition over inheritance?
Answer Looser coupling, clearer APIs, easier testing, and you can change the delegated object without changing the type hierarchy.
Simple Programs
Bank accounts — hierarchical + override
class Account:
def __init__(self, holder: str, balance: float) -> None:
self.holder = holder
self.balance = balance
def withdraw(self, amount: float) -> bool:
if amount <= 0 or amount > self.balance:
return False
self.balance -= amount
return True
def show(self) -> None:
print(f"{type(self).__name__} {self.holder}: {self.balance}")
class SavingsAccount(Account):
def add_interest(self, rate: float) -> None:
self.balance += self.balance * rate / 100
class CurrentAccount(Account):
def __init__(self, holder: str, balance: float, overdraft: float) -> None:
super().__init__(holder, balance)
self.overdraft = overdraft
def withdraw(self, amount: float) -> bool:
if amount <= 0 or amount > self.balance + self.overdraft:
return False
self.balance -= amount
return True
try:
s = SavingsAccount("Asha", 10000)
c = CurrentAccount("Ravi", 5000, 2000)
s.add_interest(5)
print(s.withdraw(20000))
print(c.withdraw(6500))
s.show()
c.show()
except Exception as e:
print("Error:", e) Employee salary with super()
class Employee:
def __init__(self, name: str, basic: float) -> None:
self.name = name
self.basic = basic
def salary(self) -> float:
return self.basic + self.basic * 0.20
class Manager(Employee):
def __init__(self, name: str, basic: float, bonus: float) -> None:
super().__init__(name, basic)
self.bonus = bonus
def salary(self) -> float:
return super().salary() + self.bonus
try:
staff = [Employee("Kiran", 30000), Manager("Asha", 50000, 15000)]
for e in staff:
print(f"{e.name} = {e.salary()}")
except Exception as e:
print("Error:", e) Multilevel toString-style chain
class Person:
def __init__(self, name: str) -> None:
self.name = name
def __str__(self) -> str:
return f"name={self.name}"
class Student(Person):
def __init__(self, name: str, roll: int) -> None:
super().__init__(name)
self.roll = roll
def __str__(self) -> str:
return f"{super().__str__()}, roll={self.roll}"
class GraduateStudent(Student):
def __init__(self, name: str, roll: int, thesis: str) -> None:
super().__init__(name, roll)
self.thesis = thesis
def __str__(self) -> str:
return f"{super().__str__()}, thesis={self.thesis}"
try:
print(GraduateStudent("Asha", 7, "AI in Healthcare"))
except Exception as e:
print("Error:", e) Vehicle rental — hierarchical polymorphism
class Vehicle:
def __init__(self, number: str) -> None:
self.number = number
def rent_per_day(self) -> int:
return 500
def rent(self, days: int) -> int:
return self.rent_per_day() * days
class Bike(Vehicle):
def rent_per_day(self) -> int:
return 300
class Car(Vehicle):
def rent_per_day(self) -> int:
return 1500
class Truck(Vehicle):
def rent_per_day(self) -> int:
return 4000
try:
fleet: list[Vehicle] = [Bike("TS09AB1234"), Car("TS10CD5678"), Truck("TS11EF9012")]
for v in fleet:
print(f"{type(v).__name__} {v.number} for 3 days = {v.rent(3)}")
except Exception as e:
print("Error:", e) Mixin: JSON-exportable models
import json
class JsonMixin:
def to_json(self) -> str:
return json.dumps(self.__dict__)
class User(JsonMixin):
def __init__(self, name: str, age: int) -> None:
self.name = name
self.age = age
try:
print(User("Ravi", 28).to_json())
except Exception as e:
print("Error:", e) Safe access — catch AttributeError
class Animal:
def speak(self) -> None:
print("...")
class Cat(Animal):
def speak(self) -> None:
print("Meow")
try:
Cat().speak()
Animal().fly() # type: ignore[attr-defined]
except AttributeError as e:
print("Error:", e) Problem Solving Tricks
- Inspect MRO anytime:
Class.__mro__orhelp(Class). - Always call
super().__init__in cooperative hierarchies. - Put mixins left of the concrete base if mixin methods should win:
class C(JsonMixin, Base). - Use
@override(Python 3.12+) or careful naming so overrides stay intentional. - Prefer composition when “is a” fails the spoken test.
boolis a subclass ofint— a classic interview surprise.- Keep inheritance trees shallow; favour many small mixins over deep chains.
- Do not call overridable methods from
__init__unless the class is designed for it. - Name-mangle only for true subclass-collision avoidance; prefer a single leading underscore for “internal”.
- For custom containers, consider
collections.UserList/UserDictinstead of subclassinglist/dictblindly.
Practice Programs List
- Single:
Mobile.call+SmartPhone.browse; call both from a SmartPhone. - Multilevel: Person → Employee → Manager; print a chained
intro(). - Hierarchical: Shape with
area(); Circle, Rectangle, Triangle in a loop. - Multiple: class that inherits LoggerMixin and Service; show MRO.
- Diamond: build A/B/C/D and print
D().ping()plus__mro__. - Override
withdrawon CurrentAccount with overdraft; assert balances. - Replace
class Playlist(list)with composition wrapping a list. - Use
isinstance/issubclasschecks in a small demo script. - Add
__slots__on a base and subclass; note attribute errors if slots omit a field. - Write a mixin
TimestampMixinthat setscreated_atin__init__via super().