Explain Codes LogoExplain Codes Logo

How do I call a parent class's method from a child class in Python?

python
method-resolution-order
multiple-inheritance
class-hierarchies
Anton ShumikhinbyAnton Shumikhin·Sep 18, 2024
TLDR

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:

class Parent: def common_method(self): print("Parent work") class Child(Parent): def common_method(self): super().common_method() # Mom! Dad! I'm calling you! print("Extended work in Child") child_instance = Child() child_instance.common_method()

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:

class Parent: def __init__(self, value): self.value = value class Child(Parent): def __init__(self, value, extra): super().__init__(value) # Parent part is done. Your turn child! self.extra = extra

Handling arguments with super()

super() showcases its versatility while managing complex arguments in parent methods by leveraging *args and **kwargs:

class Parent: def act(self, *args, **kwargs): # Perform action with variable arguments pass class Child(Parent): def act(self, *args, **kwargs): # Extraordinary behavior begins here super().act(*args, **kwargs) # Passing the baton...I mean arguments

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:

class Parent: def specific_method(self): pass class Child(Parent): def method(self): Parent.specific_method(self) # Hey ancestor, got a sec?

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.