Overriding the methods allows a user to override the parent class method. Sometimes the class provides a generic method, but in the child class, the user wants a specific implementation of the method. The name of the method must be the same in the parent class and the child class.
Let's see the program classover1.py:
class A():
def sum1(self,a,b):
print "In class A"
c = a+b
return c
class B(A):
def sum1(self,a,b):
print "In class B"
c= a*a+b*b
return c
b_obj = B()
print B.__dict__
print b_obj.sum1(4,5)
In the preceding example, classes A and B both have the same method sum1() with different implementations. We also have printed the class name space using B.__dict__. Let's see the output of the code:
Output of code classover1.py
In the preceding output, you can see the sum1 function. The Interpreter first checks the instance’s class name space: if the method is found, the interpreter uses it.