The following program will illustrates the method overriding concept onf OOP. Here parent and child classes have defined with the same method name and signature. According to context the method would be executed. The actual meaning of overriding means ignoring the parent method when both have same method signature, and executing the derived class method.
===== METHOD OVERRIDING SAMPLE PROGRAM =====
class FirstClass: #define the super class
def setdata(self, value): # define methods
self.data = value # ‘self’ refers to an instance
def display(self):
print self.data
class SecondClass(FirstClass): # inherits from FirstClass
def display(self): # redefines display
print 'Current Data = %s' % self.data
x=FirstClass() # instance of FirstClass
y=SecondClass() # instance of SecondClass
x.setdata('Before Method Overloading')
y.setdata('After Method Overloading')
x.display()
y.display()
===== Static and Class Method Sample Programs =====
class Students(object):
total = 0
def status():
print '\n Total Number of studetns is :', Students.total
status= staticmethod(status)
def __init__(self, name):
self.name= name
Students.total+=1
print ‘Before Creating instance: ‘, Students.total
student1=Students('Guido')
student2=Students('Van')
student3=Students('Rossum')
Students.status() # Accessing the class attribute through direct class name
student1.status() # Accessing the class attribute through an object
class Spam:
numinstances = 0
def count(cls):
cls.numinstances +=1
def __init__(self):
self.count()
count=classmethod(count) # Converts the count function to class method
class Sub(Spam):
numinstances = 0
class Other(Spam):
numinstances = 0
S= Spam()
y1,y2=Sub(),Sub()
z1,z2,z3=Other(),Other(),Other()
print S.numinstances, y1.numinstances,z1.numinstances
print Spam.numinstances, Sub.numinstances,Other.numinstances
No comments:
Post a Comment