The super()
function allows a subclass to access methods and properties of its parent class. It’s useful for code reuse, method overriding, and working with multiple inheritance.
Example
class Parent:
def greet(self):
return "Hello from Parent"
class Child(Parent):
def greet(self):
return super().greet() + " and Child"
c = Child()
print(c.greet())
Output:
Hello from Parent and Child
Calls the greet()
method from Parent
using super()
.
Syntax
super().method_name(arguments)
- Returns → A proxy object that allows access to parent methods.
1. Using super()
to Call Parent Methods
class Animal:
def sound(self):
return "Some sound"
class Dog(Animal):
def sound(self):
return super().sound() + " - Woof!"
d = Dog()
print(d.sound())
# Output: Some sound - Woof!
super()
calls the sound()
method from Animal
.
2. Using super()
in __init__()
to Inherit Attributes
class Person:
def __init__(self, name):
self.name = name
class Employee(Person):
def __init__(self, name, role):
super().__init__(name) # Call Parent's __init__()
self.role = role
e = Employee("Alice", "Manager")
print(e.name, e.role)
# Output: Alice Manager
Uses super()
to initialize the parent class attributes.
3. Calling super()
with Multiple Inheritance
class A:
def show(self):
return "A"
class B(A):
def show(self):
return super().show() + " B"
class C(B):
def show(self):
return super().show() + " C"
c = C()
print(c.show())
# Output: A B C
super()
calls methods in the inheritance chain.
4. Using super()
with Multiple Parent Classes
class Parent1:
def greet(self):
return "Hello from Parent1"
class Parent2:
def greet(self):
return "Hello from Parent2"
class Child(Parent1, Parent2):
def greet(self):
return super().greet() # Calls Parent1's method (left-most parent)
c = Child()
print(c.greet())
# Output: Hello from Parent1
Python follows the “Method Resolution Order” (MRO).
5. Getting MRO Order (super()
Works in This Order)
class A: pass
class B(A): pass
class C(A): pass
class D(B, C): pass
print(D.mro())
Output:
[<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]
Shows the method resolution order for super()
.
Key Notes
- ✔ Calls methods from the parent class.
- ✔ Works with method overriding.
- ✔ Supports multiple inheritance via MRO.
- ✔ Used in constructors (
__init__()
) to initialize parent attributes.
By using super()
, you can reuse code, extend parent functionality, and manage multiple inheritance efficiently. 🚀