Super() Method Usage
Understanding super() in Python
The super()
method is a powerful tool in Python for calling methods from parent classes, especially in complex inheritance scenarios.
Basic super() Syntax
class Parent:
def __init__(self, name):
self.name = name
def greet(self):
print(f"Hello from {self.name}")
class Child(Parent):
def __init__(self, name, age):
super().__init__(name) ## Call parent's __init__ method
self.age = age
def greet(self):
super().greet() ## Call parent's greet method
print(f"I am {self.age} years old")
## Usage
child = Child("Alice", 10)
child.greet()
super() in Multiple Inheritance
class A:
def method(self):
print("Method from A")
class B:
def method(self):
print("Method from B")
class C(A, B):
def method(self):
super().method() ## Follows Method Resolution Order (MRO)
## Demonstrating MRO
c = C()
c.method()
Method Resolution Order (MRO)
flowchart TD
A[Method Call] --> B{Check Current Class}
B --> |Not Found| C[Check Parent Classes]
C --> D[Follow MRO Sequence]
D --> E[Execute First Matching Method]
super() Usage Patterns
Pattern |
Description |
Example |
Calling Parent Constructor |
Initialize parent class attributes |
super().__init__() |
Method Overriding |
Extend parent class method |
super().method() |
Multiple Inheritance |
Navigate complex inheritance |
super().method() |
Advanced super() Techniques
class BaseCalculator:
def calculate(self, x, y):
return x + y
class AdvancedCalculator(BaseCalculator):
def calculate(self, x, y, z=0):
base_result = super().calculate(x, y)
return base_result + z
## Usage
calc = AdvancedCalculator()
print(calc.calculate(5, 3)) ## 8
print(calc.calculate(5, 3, 2)) ## 10
Common Mistakes to Avoid
class Parent:
def __init__(self, value):
self.value = value
class Child(Parent):
def __init__(self, value):
## INCORRECT: Missing super() call
## self.value = value
def __init__(self, value):
## CORRECT: Using super()
super().__init__(value)
Best Practices
- Always use
super()
in multi-level or multiple inheritance
- Understand the Method Resolution Order
- Use
super()
to ensure all parent class initializations are complete
At LabEx, we emphasize the importance of mastering super()
for writing clean, maintainable Python code.