Demystifying Python’s super() function
Table of Contents
By Invented Reporter | MONTREAL – 2025/06/18 01:33:10
The super() function in Python is a built-in that allows you to call methods from a parent class. It’s particularly useful in scenarios involving inheritance, especially multiple inheritance, to avoid explicitly naming the parent class [[1]].
How super() Works
In single inheritance, super() simplifies calling a parent’s method. However, its power truly shines with multiple inheritance. When dealing with multiple inheritance, Python uses Method Resolution Order (MRO) to determine the order in which parent classes are searched for a method [[1]].
“Now call to super in init defined in First will continue searching MRO and find init defined in Second, and any call to super will hit the default object init.” [[1]]
Consider this example:
class First:
def __init__(self):
print("First init")
super().__init__()
class Second:
def __init__(self):
print("Second init")
super().__init__()
class Combined(First,Second):
def __init__(self):
print("Combined init")
super().__init__()
instance = Combined()
In this case, the MRO would be [combined, First, Second, object]. When super().__init__() is called in Combined, it calls First.__init__(). Then, super().__init__() in First calls Second.__init__(). super().__init__() in Second calls the object class’s init method [[1]].
Python 2 vs. Python 3
In Python 2, using super() required specifying the class and instance explicitly, which could be confusing. Python 3 simplifies this by allowing super() to be called without arguments [[2]].
# Python 2
super(CurrentClass, self).__init__()
# Python 3
super().__init__()
Common Issues
One common issue is encountering the error 'super' object has no attribute '__sklearn_tags__'. This can occur when using libraries like Scikit-learn and XGBoost, possibly due to compatibility issues or Python version. Ensuring you have the latest versions of these libraries might resolve the problem [[3]].
frequently Asked Questions
- What is the purpose of
super()in Python? super()allows you to call methods from a parent class, especially useful in inheritance scenarios.- How does
super()work with multiple inheritance? - Python uses Method Resolution Order (MRO) to determine the order in which parent classes are searched for a method when using
super(). - What is the difference between
super()in Python 2 and Python 3? - Python 3 simplifies the syntax by allowing
super()to be called without arguments, unlike Python 2 which requires specifying the class and instance.
Sources
- Stack Overflow: How does Python’s super () work with multiple inheritance?
- Stack Overflow: What does ‘super’ do in Python?
- Stack Overflow: ‘super’ object has no attribute ‘__sklearn_tags__’
- Oracle: Inheritance (Java Documentation)
- ACM Digital Library: Object-Oriented Concepts, Databases, and Applications
- Consortium for Software Engineering Research (CSER)
- IEEE
