The super()
function in Python is used to call methods from a parent class from within a method of a child class. It is commonly used in object-oriented programming to extend or modify the behavior of inherited methods.
1. Basic Usage of super()
The super()
function is often used in the constructor method (__init__
) to initialize the parent class:
class Parent:
def __init__(self, name):
self.name = name
def greet(self):
return f"Hello, my name is {self.name}."
class Child(Parent):
def __init__(self, name, age):
super().__init__(name)
self.age = age
def greet(self):
parent_greeting = super().greet()
return f"{parent_greeting} I am {self.age} years old."
# Example usage
child = Child("Alice", 10)
print(child.greet())
# Output: Hello, my name is Alice. I am 10 years old.
2. Understanding super()
Parameters
super()
can be called with different parameters depending on the context:
class Parent:
def __init__(self, name):
self.name = name
def greet(self):
return f"Hello, my name is {self.name}."
class Child(Parent):
def __init__(self, name, age):
super().__init__(name)
self.age = age
def greet(self):
# super() can be called with explicit parameters if needed
return super(Child, self).greet() + f" I am {self.age} years old."
# Example usage
child = Child("Bob", 12)
print(child.greet())
# Output: Hello, my name is Bob. I am 12 years old.
3. Using super()
in Multiple Inheritance
In multiple inheritance scenarios, super()
helps in managing method resolution order (MRO):
class A:
def __init__(self):
print("A init")
def hello(self):
print("Hello from A")
class B(A):
def __init__(self):
super().__init__()
print("B init")
def hello(self):
super().hello()
print("Hello from B")
class C(A):
def __init__(self):
super().__init__()
print("C init")
def hello(self):
super().hello()
print("Hello from C")
class D(B, C):
def __init__(self):
super().__init__()
print("D init")
def hello(self):
super().hello()
print("Hello from D")
# Example usage
d = D()
d.hello()
# Output:
# A init
# C init
# B init
# D init
# Hello from C
# Hello from B
# Hello from D
4. Conclusion
The super()
function is a powerful feature in Python that allows you to call methods from a parent class, facilitating code reuse and helping manage complex inheritance hierarchies. Understanding its usage in different contexts can greatly improve the design and functionality of your object-oriented programs.