Python – Method Overriding

If we write method of same name in the both classes, parent class as well as in the child class then the parent class’s method will not be available to the child class.

In this case only child class’s method is accessible only which means child class’s method is replacing parent class’s method.

Method overriding is used when programmer want to modify the existing behavior of a method.

Method overriding is required sometimes because you may want special or different functionality in you subclass.

Let look at the below example.

class Parent:
    def myMethod(self):
        print("Calling Parent Class Method.")

class Child(Parent):
    def myMethod(self):
        print("Calling Child Class Method.")


obj = Child()
obj.myMethod()

#OUTPUT
Calling Child Class Method.

In the above example, you can clearly check that “Child class overrides the method written in Parent class”.

Method with Super() Method

super() method is used to call parent class’s constructor or methods from the child class.

Syntax: super().method_name()

class Add:
    def result(self, x,y):
        print('Addition: ', x+y)

class Multi(Add):
    def result(self, a,b):
        super().result(a,b)
        print('Mulitplication: ', a*b)

obj = Multi()
obj.result(10,4)

#OUTPUT
Addition:  14
Mulitplication:  40
Wordpress Social Share Plugin powered by Ultimatelysocial
Wordpress Social Share Plugin powered by Ultimatelysocial