Python Notes
Master Python inheritance — single, multiple, multilevel, and hierarchical inheritance, MRO (Method Resolution Order), super(), mixins, and real-world class hierarchies.
🧠 Real-World Analogy — Family Tree
Think of your family tree — Grandfather → Father → You. You inherit some properties from your father (height, blood group), and your father from his father. This is inheritance. In code: a child class (derived class) automatically inherits properties and methods from a parent class (base class). The child can use those properties and also override or extend them.
1️⃣ Single Inheritance
class Animal:
def __init__(self, name, sound):
self.name = name
self.sound = sound
self.energy = 100
def speak(self):
print(f"{self.name} says: {self.sound}!")
def eat(self, food):
self.energy += 20
print(f"{self.name} eats {food}. Energy: {self.energy}")
def sleep(self):
self.energy += 30
print(f"{self.name} sleeps. Energy: {self.energy}")
def __str__(self):
return f"Animal({self.name})"
class Dog(Animal): # ← Dog inherits from Animal
def __init__(self, name, breed):
super().__init__(name, "Woof") # call parent __init__
self.breed = breed
def fetch(self, item):
self.energy -= 10
print(f"{self.name} fetches the {item}! Energy: {self.energy}")
def __str__(self):
return f"Dog({self.name}, {self.breed})"
buddy = Dog("Buddy", "Labrador")
buddy.speak() # inherited from Animal
buddy.eat("kibble") # inherited from Animal
buddy.fetch("ball") # Dog-specific
buddy.sleep() # inherited from Animal
print(buddy)
# Check types
print(isinstance(buddy, Dog)) # True
print(isinstance(buddy, Animal)) # True — IS-A relationship
print(issubclass(Dog, Animal)) # TrueOutput:
| Buddy says | Woof! |
| Buddy eats kibble. Energy | 120 |
| Buddy fetches the ball! Energy | 110 |
| Buddy sleeps. Energy | 140 |
2️⃣ Multilevel Inheritance
class Vehicle:
def __init__(self, make, model):
self.make = make
self.model = model
self.speed = 0
def accelerate(self, amount):
self.speed += amount
print(f"{self.make} {self.model} accelerates to {self.speed} km/h")
def brake(self):
self.speed = max(0, self.speed - 20)
print(f"Braking... {self.speed} km/h")
class Car(Vehicle):
def __init__(self, make, model, doors=4):
super().__init__(make, model)
self.doors = doors
def honk(self):
print(f"{self.make} {self.model}: Beep beep! 🚗")
class ElectricCar(Car): # ← multilevel: ElectricCar → Car → Vehicle
def __init__(self, make, model, battery_kwh):
super().__init__(make, model)
self.battery_kwh = battery_kwh
self.charge_percent = 80
def charge(self):
self.charge_percent = 100
print(f"⚡ {self.make} {self.model} fully charged! ({self.battery_kwh} kWh)")
def range_km(self):
return int(self.battery_kwh * 6 * self.charge_percent / 100)
def status(self):
print(f"🔋 Battery: {self.charge_percent}% | Range: {self.range_km()} km")
tesla = ElectricCar("Tesla", "Model 3", 75)
tesla.accelerate(60) # from Vehicle
tesla.honk() # from Car
tesla.charge() # from ElectricCar
tesla.status()Output:
3️⃣ Hierarchical Inheritance
Output:
4️⃣ Multiple Inheritance
Output:
| Donald says | Quack! |
| Donald eats breadcrumbs. Energy | 120 |
| MRO | ['Duck', 'Animal', 'Flyable', 'Swimmable', 'object'] |
🔀 Method Resolution Order (MRO)
With multiple inheritance, Python needs to decide which method gets called first. This is determined by the MRO (Method Resolution Order) — the C3 linearization algorithm ensures a consistent, predictable order.
Diamond Problem:
A
/ \
B C
\ /
D
MRO: D → B → C → A → objectclass A:
def greet(self): print("Hello from A")
class B(A):
def greet(self): print("Hello from B")
class C(A):
def greet(self): print("Hello from C")
class D(B, C): # multiple inheritance
pass
d = D()
d.greet() # which greet() gets called?
print(D.__mro__)
# (<class 'D'>, <class 'B'>, <class 'C'>, <class 'A'>, <class 'object'>)Output:
Hello from B
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)Python resolves left-to-right, depth-first, with each class appearing only once.
🧩 Mixin Pattern
A Mixin is a small class that provides only one specific feature — inherit it to add that feature to your main class.
Output:
| [HH | MM:SS] [Employee] Employee record created. |
| [HH | MM:SS] [Employee] Salary raised by 15%. New salary: ₹86,250 |
| "name" | "Arjun Sharma", |
| "emp_id" | "EMP001", |
| "department" | "Engineering", |
| "salary" | 86250.0 |
🏦 Real-World Example — Banking Hierarchy
Output:
| + Deposited ₹10,000 | Balance | ₹60,000 |
| - Withdrew ₹5,000 | Balance | ₹55,000 |
| 💰 Interest (5.5%) | +₹3025.00 | Balance: ₹58025.00 |
| - Withdrew ₹3,000 | Balance | ₹-1,000 ⚠️ Overdraft |
🇮🇳 Hindi Explanation (हिंदी में समझें)
Inheritance kya hai? Inheritance is a mechanism where one class (child) can use another class's (parent) attributes and methods — without rewriting them. It's the most powerful technique for code reuse.
Why do we usesuper()?super()lets us call parent class methods from within a child class. This is especially important in__init__to ensure parent class attributes are also initialized.
MRO kya hai? With multiple inheritance, Python uses the C3 Linearization algorithm to determine a fixed order for which class's method gets called first. You can view this order with ClassName.__mro__.Mixin kya hai? A Mixin is a small class that provides just one specific feature (like JSON conversion or logging). You can easily add that feature to multiple classes by inheriting the mixin.
❓ Interview Questions
Q1: What is inheritance? What problem does it solve?
Answer: Inheritance allows a child class to acquire attributes and methods of a parent class. It solves the DRY (Don't Repeat Yourself) problem — common behavior is defined once in the base class and reused across all subclasses. It also models the IS-A relationship (e.g., a Dog IS-A Animal).
Q2: Explain the different types of inheritance in Python.
Answer:
- Single:
class B(A)— one parent - Multiple:
class C(A, B)— two or more parents - Multilevel:
class C(B)whereclass B(A)— chain - Hierarchical: Multiple classes inherit from one parent
- Hybrid: Combination of multiple + multilevel
Q3: What is MRO and how does Python calculate it?
Answer: MRO (Method Resolution Order) defines the order in which Python searches classes when calling a method. Python uses the C3 Linearization algorithm:
- Start with the current class
- Follow left-to-right depth-first, but each class appears only once
- Always respects the inheritance order
Use ClassName.__mro__ or ClassName.mro() to inspect it.
Q4: What is the diamond problem? How does Python handle it?
Answer: The diamond problem occurs in multiple inheritance when two parent classes share a common ancestor. Without MRO, it's ambiguous which grandparent method to call. Python's C3 MRO ensures each class appears exactly once in a predictable order, eliminating ambiguity.
Q5: When should you use super() vs calling the parent directly?
Answer: Always prefer super() over ParentClass.method(self) because:
super()respects MRO in multiple inheritance- It avoids hardcoding the parent class name
- Direct calls can break in multiple-inheritance hierarchies
Q6: What is the difference between isinstance() and issubclass()?
Answer:
isinstance(obj, Class)— checks ifobjis an instance ofClassor any subclassissubclass(ChildClass, ParentClass)— checks ifChildClassis a subclass ofParentClass
Q7: What is a Mixin? Give an example use case.
Answer: A Mixin is a class designed to add specific functionality to other classes via inheritance without being a standalone base class. Example: a JSONMixin that adds to_json() to any class, or a LogMixin that adds log(). They're used to compose behavior rather than build deep hierarchies.
🧪 Practice Exercises
- School Hierarchy: Create
Person→Employee→TeacherandStudentwith appropriate attributes and methods. - Vehicle Family: Create
Vehicle→LandVehicle→Car,Truck; andVehicle→WaterVehicle→Boat,Ship. - E-Commerce Products: Create
Product→Electronics,Clothing,Foodeach with category-specific attributes. - Mixin Composition: Create
TimestampMixin(addscreated_at,updated_at),AuditMixin(logs changes), and apply both to aBlogPostclass. - Override Bank: Override
withdraw()in aFixedDepositAccountto raise an exception if the account is less than 1 year old.
💡 Next Topic → Polymorphism: One name, many forms — learn duck typing, method overriding, operator overloading, and the power of polymorphic code.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Inheritance in Python.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Python Master Course topic.
Search Terms
python-master-course, python master course, python, master, course, object, oriented, programming
Related Python Master Course Topics