Overriding Methods in Python

PythonServer Side ProgrammingProgramming

You can always override your parent class methods. One reason for overriding parent's methods is because you may want special or different functionality in your subclass.

Example

 Live Demo

#!/usr/bin/python
class Parent: # define parent class
   def myMethod(self):
      print 'Calling parent method'
class Child(Parent): # define child class
   def myMethod(self):
      print 'Calling child method'
c = Child()    # instance of child
c.myMethod()   # child calls overridden method

Output

When the above code is executed, it produces the following result −

Calling child method
raja
Published on 30-Jan-2020 07:19:31
Advertisements