Python: Call Parent class method

Python: Call Parent class method

In Python, when working with classes and inheritance, you can call a method of a parent (or superclass) from a child (or subclass) using the super() function or directly using the name of the parent class. Here's how to do it:

1. Using super():

The super() function is used to call a method from the parent class. This is especially useful when you have overridden a method in the child class but still want to call the original method in the parent class.

class Parent: def show(self): print("This is the Parent class method!") class Child(Parent): def show(self): super().show() # Call the 'show' method of the Parent class print("This is the Child class method!") c = Child() c.show() # Output: # This is the Parent class method! # This is the Child class method! 

2. Using the parent class name:

You can also directly use the parent class name to call its method. However, this approach is less flexible than using super(), especially when dealing with multiple inheritance.

class Parent: def show(self): print("This is the Parent class method!") class Child(Parent): def show(self): Parent.show(self) # Call the 'show' method of the Parent class print("This is the Child class method!") c = Child() c.show() # Output: # This is the Parent class method! # This is the Child class method! 

In most cases, using super() is recommended because it provides a more dynamic way of accessing parent class methods, especially in situations involving multiple inheritance or when the class hierarchy might change.


More Tags

android-pendingintent laravel-artisan overflow android-query angularjs-ng-click nouislider big-o responsive gulp react-scripts

More Programming Guides

Other Guides

More Programming Examples