Understanding Python's super() Function and Method Resolution Order (MRO)
This article explains how Python's super() function works, its syntax differences between Python 2 and 3, provides code examples, and details how the method resolution order (MRO) determines the sequence of parent class method calls in single and multiple inheritance scenarios.
The super() function in Python is used to call methods from a parent (or next) class in the method resolution order (MRO), helping to resolve issues in multiple inheritance such as diamond problems.
Syntax: super(type[, object-or-type]) , where type is the class and the optional second argument is usually self . In Python 3 the arguments can be omitted, allowing super().method() , while Python 2 requires explicit arguments.
Examples for Python 3:
class A:
pass
class B(A):
def add(self, x):
super().add(x)Example for Python 2:
class A(object): # inherit object in Python 2
pass
class B(A):
def add(self, x):
super(B, self).add(x)A more complete example demonstrates how super() works with multiple inheritance. Classes Root , B , C , and D are defined, and creating an instance of D shows the order of __init__ calls (B → C → Root) as dictated by the MRO.
class Root(object):
def __init__(self):
print("this is Root")
class B(Root):
def __init__(self):
print("enter B")
super(B, self).__init__()
print("leave B")
class C(Root):
def __init__(self):
print("enter C")
super(C, self).__init__()
print("leave C")
class D(B, C):
pass
d = D()
print(d.__class__.__mro__)The article also notes important caveats: super() works only with new‑style classes, can behave unexpectedly in complex multiple‑inheritance hierarchies, and should be used consistently (either always with super() or always with explicit class calls) to avoid duplicate or missed method calls.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.