Python
Python Basics
- Introduction to Python and Its History
- Python Syntax and Indentation
- Python Variables and Data Types
- Dynamic and Strong Typing
- Comments and Docstrings
- Taking User Input (input())
- Printing Output (print())
- Python Operators (Arithmetic, Logical, Comparison)
- Type Conversion and Casting
- Escape Characters and Raw Strings
Data Structures in Python
- Lists
- Dictionaries
- Dictionary Comprehensions
- Strings and String Manipulation
- Tuples
- Python Sets: Unordered Collections
- List Comprehensions and Generator Expressions
- Set Comprehensions
- String Formatting
- Indexing and Slicing
Control Flow and Loops
- Conditional Statements: if, elif, and else
- Loops and Iteration
- While Loops
- Nested Loops
- Loop Control Statements
- Iterators and Iterables
- List, Dictionary, and Set Iterations
Functions and Scope
- Defining and Calling Functions (`def`)
- Function Arguments (`*args`, `**kwargs`)
- Default Arguments and Keyword Arguments
- Lambda Functions
- Global and Local Scope
- Function Return Values
- Recursion in Python
Object-Oriented Programming (OOP)
- Object-Oriented Programming
- Classes and Objects
- the `__init__()` Constructor
- Instance Variables and Methods
- Class Variables and `@classmethod`
- Encapsulation and Data Hiding
- Inheritance and Subclasses
- Method Overriding and super()
- Polymorphism
- Magic Methods and Operator Overloading
- Static Methods
- Abstract Classes and Interfaces
Python Programs
- Array : Find median in an integer array
- Array : Find middle element in an integer array
- Array : Find out the duplicate in an array
- Array : Find print all subsets in an integer array
- Program : Array : Finding missing number between from 1 to n
- Array : Gap and Island problem
- Python Program stock max profit
- Reverse words in Python
- Python array duplicate program
- Coin change problem in python
- Python Write fibonacci series program
- Array : find all the pairs whose sum is equal to a given number
- Find smallest and largest number in array
- Iterate collections
- List comprehensions
- Program: Calculate Pi in Python
- String Formatting in Python
Method Overriding and super()
in Python
Object-Oriented Programming (OOP) is one of the most important paradigms in Python. If you’ve already explored basic concepts like classes and inheritance, it’s time to take it a step further and learn how to override methods and use the built-in super()
function.
These features allow child classes to modify or extend the behavior of parent classes, making your code more flexible and powerful.
In this guide, we’ll explore:
- What method overriding is,
- Why it’s useful,
- How to use
super()
effectively, - And practical examples that bring these ideas to life.
Let’s get started.
What Is Method Overriding in Python?
Method overriding happens when a child class defines a method with the same name as a method in its parent class. When you create an object of the child class, the overridden method in the child class gets called instead of the one in the parent.
This is Python’s way of allowing you to customize or replace inherited behavior.
Basic Example of Method Overriding
class Animal: def speak(self): return "The animal makes a sound"
class Dog(Animal): def speak(self): return "The dog barks"
animal = Animal()dog = Dog()
print(animal.speak()) # Output: The animal makes a soundprint(dog.speak()) # Output: The dog barks
Here, both classes have a speak()
method, but the one in the child class (Dog
) overrides the one from the parent class (Animal
).
Why Use Method Overriding?
- ✅ Customization: You can change how inherited methods behave for specific subclasses.
- ✅ Polymorphism: It allows you to write general code that works with different class types.
- ✅ Extensibility: Makes your code flexible and scalable as your project grows.
How Python Resolves Method Calls
Python uses a rule called Method Resolution Order (MRO). When you call a method on an object, Python looks for it in the object’s class first. If it’s not found, it checks the parent class, and so on.
When you override a method, Python simply finds and uses the version in the child class before it even reaches the parent.
Using super()
in Python
Sometimes, while overriding a method, you still want to keep some behavior from the parent class. This is where the super()
function comes in.
The super()
function allows you to call the parent class’s version of a method from the child class.
Basic Example of super()
class Animal: def speak(self): return "The animal makes a sound"
class Dog(Animal): def speak(self): original_sound = super().speak() return f"{original_sound} and the dog barks"
dog = Dog()print(dog.speak())
Output:
The animal makes a sound and the dog barks
Here, the child class Dog
extends the behavior of the parent method instead of replacing it entirely.
How super()
Works Behind the Scenes
- It returns a proxy object that delegates method calls to a parent or sibling class.
- Works especially well in multiple inheritance.
- Ensures your code respects Python’s Method Resolution Order (MRO).
Example: Constructor Overriding with super()
super()
is often used in constructors (__init__
) when you want a child class to initialize both its own attributes and those from the parent.
class Person: def __init__(self, name): self.name = name
class Student(Person): def __init__(self, name, student_id): super().__init__(name) # Call parent constructor self.student_id = student_id
s = Student("Alice", "S123")print(s.name) # Aliceprint(s.student_id) # S123
This approach avoids repeating code and ensures consistent initialization across classes.
Real-World Analogy
Imagine a generic Vehicle
class with a start_engine()
method. Now, you create a Car
class that overrides this method to add “seatbelt check” before starting. But you still want the original engine-starting logic too. That’s where super()
shines.
Advanced Example: Logging Activity Using super()
class Logger: def log(self, message): print(f"Log: {message}")
class FileLogger(Logger): def log(self, message): super().log(message) print(f"Writing '{message}' to a file...")
logger = FileLogger()logger.log("System started")
Output:
Log: System startedWriting 'System started' to a file...
This shows how you can layer behavior—log to the console and then to a file—all using super()
.
Best Practices
- ✅ Use
super()
for cleaner and safer inheritance. - ✅ Always override only when necessary.
- ❌ Don’t override methods just for the sake of it—prefer clarity.
- ✅ Use descriptive method names in child classes when you don’t intend to override.
Common Mistakes and How to Avoid Them
Mistake | Why It’s a Problem | Fix |
---|---|---|
Forgetting super() in __init__() | Parent class attributes won’t initialize | Always call super().__init__() |
Calling super() incorrectly in multiple inheritance | Can break MRO | Follow Python’s MRO and class hierarchy |
Overriding method without extending needed behavior | Might lose important functionality | Use super() to preserve parent behavior |
Method Overriding vs Method Overloading
Concept | Python Support | Description |
---|---|---|
Method Overriding | ✅ Yes | Same method name in child class |
Method Overloading | ❌ Not directly | Python does not support true overloading; use default args instead |
Conclusion
Understanding method overriding and how to use super()
is crucial for writing efficient and maintainable Python code. These features allow you to:
- Customize inherited behavior,
- Avoid code duplication,
- And build flexible class hierarchies.
Whether you’re building a school management system, a game, or a payment platform, these concepts help you stay organized and keep your logic clean.
So next time you create a subclass in Python, ask yourself:
“Do I need to override this method? And should I call the parent’s version with
super()
?”
Once you get the hang of it, you’ll wonder how you ever wrote OOP code without it!