Thursday, 26 January 2017

METHOD OVERRIDING IN PYTHON

The concept of defining multiple methods with the same name and with the same number of parameters. One is in super class and another is in sub class is known as Method Overriding.

Example –
class Parent:
   
def m1(self):
       
print 'calling parent method'
class
Child(Parent):
   
def m1(self):
       
print 'calling child method'
C=Child()
C.m1()
P=Parent()
P.m1()

Output –
calling child method
calling parent method


super() - When method overriding

Example –
class Parent(object):
   
def altered(self):
       
print 'parent altered'
class
Child(Parent):
   
def altered(self):
       
print 'child altered'
       
super(Child,self).altered()
       
print 'Child.Alter after Parent altered'
dad=Parent()
son=Child()
dad.altered()
son.altered()

Output –
parent altered
child altered
parent altered
Child.Alter after Parent altered

No comments:

Post a Comment