Python Notes
Deep dive into Python method overriding — redefining parent class methods in child classes, using super(), cooperative multiple inheritance, MRO interaction, and real-world design patterns.
🧠 Real-World Analogy — Company Policy
A company has a general HR policy — uniform leave rules for all employees. But the Engineering department manager has added extra rules for their team — "remote work on Fridays." The special rule applies to engineering employees; the general policy applies to everyone else. This is method overriding — a child class redefines its parent's method to provide new behavior.
✅ Basic Method Overriding
Output:
| I am Rex. Rex says | Woof! 🐕 Rex runs on 4 legs. |
| I am Whiskers. Whiskers says | Meow! 🐈 Whiskers slinks silently. |
| I am Nagraj. Nagraj hisses | Ssss! 🐍 Nagraj slithers. |
🔗 Overriding with super() — Extending Parent Behavior
Sometimes you need to do the parent's work and add something extra — with super() you call the parent method and then add your own logic on top.Output:
| [E001] Rahul Kumar | Salary | ₹ 50,000.00 |
| [E002] Sneha Singh | Salary | ₹ 55,000.00 |
| [M001] Arjun Sharma | Salary | ₹ 90,000.00 | Team: 8 people | Role: Manager |
| [M002] Priya Mehta | Salary | ₹ 95,000.00 | Team: 12 people | Role: Manager |
| [D001] Vikram Nair | Salary | ₹ 150,000.00 | Team: 30 people | Role: Director |
🎮 Game Characters — Override Chain
⚠️ Preventing Override — Convention
Python has no final keyword, but you can signal "do not override" using conventions or raise errors:class Base:
def important_method(self):
"""Do NOT override this method."""
return "Critical base logic"
def _sealed_operation(self):
# Raise error if child tries to call super's version
raise NotImplementedError("This method must not be overridden.")
# Or use a decorator convention:
def final(method):
"""Decorator marking a method as 'final' (no override)."""
method.__is_final__ = True
return method
class Base2:
@final
def calculate(self):
return 42
class Child2(Base2):
def calculate(self): # overriding anyway — but code reviewer can check __is_final__
return 99
# Check at runtime:
print(getattr(Base2.calculate, "__is_final__", False)) # True🔀 Cooperative Multiple Inheritance with super()
Output:
🇮🇳 Hindi Explanation (हिंदी में समझें)
Method Overriding kya hai? When a child class redefines a method with the same name as its parent class — to provide new or modified behavior — that's method overriding. This is how runtime polymorphism works.
Why do we usesuper()in overriding? Often you need both the parent's work (super().method()) and your own extra logic on top.super()lets you reuse the parent's work without wasting it — you reuse and extend.
How doessuper()work in multiple inheritance?super()works according to MRO (Method Resolution Order) — it doesn't call the "parent" class, but the next class in the MRO. That's why cooperative patterns withsuper()are important in multiple inheritance.
❓ Interview Questions
Q1: What is method overriding? How is it different from overloading?
Answer:
- Overriding: Child class redefines a parent class method with the same name and signature. Runtime polymorphism — which version runs depends on the actual object type.
- Overloading: Same method name, different parameters (Python doesn't support true overloading — use defaults/
*argsinstead).
Q2: When should you call super() in an overriding method?
Answer: Call super() when you want to extend (not replace) the parent's behavior. Examples: __init__ almost always needs super().__init__() to initialize parent attributes. Business methods should call super() when base logic should still run plus new logic.
Q3: What happens if a child class doesn't call super().__init__()?
Answer: The parent's __init__ never runs, so parent attributes are never initialized. Calling any inherited method that depends on those attributes will raise AttributeError. Always call super().__init__() unless you deliberately want to skip parent initialization.
Q4: Can you call a grandparent's method directly, skipping the parent?
Answer: Yes, explicitly: GrandParent.method(self). But this defeats the purpose of cooperative inheritance and breaks MRO. Prefer super() and design the hierarchy so MRO does the right thing.
Q5: What is cooperative multiple inheritance?
Answer: Each class in the MRO chain calls super().method(), passing control cooperatively down the chain. Every class's version of the method runs once, in MRO order, until object is reached. This requires all classes to use super() consistently.
Q6: How can you check if a method has been overridden?
Answer:
Dog.speak is Animal.speak # False — overridden
Cat.speak is Animal.speak # False
# or
type(obj).speak is Animal.speak # False means overriddenQ7: What is method shadowing vs method overriding?
Answer: Same concept — a subclass defines a method with the same name as the parent. "Shadowing" emphasizes that the parent's version is hidden (shadowed) by the child's version. In Python, they're the same thing.
🧪 Practice Exercises
- Animal Symphony: Create
Animalwithspeak()returning a generic sound. Override inDog,Cat,Lion,Parrotwith specific sounds + emoji. AddGoldenRetriever(Dog)that callssuper().speak()then adds "...and wags tail!". - Tax Calculator:
Employee.tax()= 10%. Override inSeniorEmployee(8%),Director(15%),Contractor(20%). All callsuper()and add a role-specific surcharge. - Logging Mixin Chain: Stack 3 mixins on a
DatabaseModel.save()—AuditMixin(timestamp),ValidationMixin(check required fields),CacheMixin(invalidate cache). All use cooperativesuper(). - Vending Machine: Base
VendingMachine.dispense()— override inSnackMachine,DrinkMachine,CoffeeMachine. Each callssuper()for base checks then adds product-specific logic. - Shipping Cost: Override
calculate_cost()in a 4-level hierarchy:BaseShipping→DomesticShipping→ExpressShipping→SameDayShippingwith each callingsuper()and adding its surcharge.
💡 Next Topic → Magic Methods: Unlock Python's full power with dunder methods —__init__,__str__,__repr__,__len__,__add__,__eq__,__lt__,__getitem__,__iter__and more!
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Method Overriding 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