July 2024
Beginner
5 pages
5m
English
You want to invoke a method in a parent class in place of a method that has been overridden in a subclass.
To call a method in a parent (or superclass), use the super() function.
For example:
classA(object):defspam(self):('A.spam')classB(A):defspam(self):('B.spam')super().spam()# Call parent spam()
A very common use of super() is in the handling
of the __init__() method to make sure that parents are
properly initialized:
classA(object):def__init__(self):self.x=0classB(A):def__init__(self):super().__init__()self.y=1
Another common use of super() is in code that overrides any
of Python’s special methods. For example:
classProxy(object):def__init__(self,obj):self._obj=obj# Delegate attribute lookup to internal objdef__getattr__(self,name):returngetattr(self._obj,name)# Delegate attribute assignmentdef__setattr__(self,name,value):ifname.startswith('_'):super().__setattr__(name,value)# Call original __setattr__else:setattr(self._obj,name,value)
In this code, the implementation of __setattr__() includes
a name check. If the name starts with an underscore (_), it invokes
the original implementation of __setattr__() using super().
Otherwise, it delegates to the internally held object self._obj ...
Read now
Unlock full access