How do I call a parent class's method from a child class in Python?
super()
is your go-to function to access the parent class methods from a child class, it provides a simple and efficient way to call overridden methods.
Example:
Output:
Parent work
Extended work in Child
By using super()
, the method call is delegated to the parent or superclass without explicitly naming it, making it particularly useful for dealing with multiple inheritance and creating extendable code.
Walking through super()
The super()
function acts as a powerful tool in offering readability and maintainability in your codebase, especially while dealing with deep class hierarchies. It smartly handles the whole Method Resolution Order (MRO), outlining the sequence in which base classes are sought out when executing a method.
Constructors and super()
When initializing objects, super()
aids in calling the parent's constructor smoothly:
Handling arguments with super()
super()
showcases its versatility while managing complex arguments in parent methods by leveraging *args
and **kwargs
:
Direct calls to ancestral methods
Despite super()
's convenience, Python allows direct method calls to a parent using the class name. It's not as dynamic as super()
, but can do the trick when required:
Super() for the rescue in Python 2
While working with Python 2.x, ensure to use new-style classes (by inheriting from object
) for super()
to function correctly. Python 3 users can breathe easy as all classes are "new-style" by default.
The 'not-so-super' situations with super()
super()
is no magic bullet and should be used wisely. It might lead to unexpected behavior in certain situations of multiple inheritance if all base classes are not designed to collaborate. A solid understanding of the MRO and compatible methods across base classes should prevent these hiccups.
Sorting method resolution with super()
Think of Python MRO as an orderly process in a thriving factory, and super()
as the efficient manager, making sure the 'manufacturing process' or method call, travels smoothly along the assembly line.
Why the fuss about super()?
super()
simplifies our lives by removing the need for explicit class names, avoiding redundancy and making the code more maintainable. This improves method organization, especially when dealing with multiple inheritance.
Ascending beyond direct ancestors
Moreover, super()
isn't just limited to direct parent-child calls. It can be used to call methods from any class in the preceding sequence of the MRO, even if that class isn't a direct ancestor.
Was this article helpful?