Extend Class Method in Python
Last Updated :
06 Feb, 2020
In Python, when a subclass defines a function that already exists in its superclass in order to add some other functionality in its own way, the function in the subclass is said to be an extended method and the mechanism is known as extending. It is a way by which Python shows Polymorphism. This is similar to overriding in Java and virtual methods in C++. A call from the instance of the subclass executes the subclass’s version of the function. To call superclass’s version super()
method is used.
Why Extend a Function?
The goal of extending a class method in Python can be achieved by Inheritance. One of the major advantages provided by extending a method is that it makes the code reusable. Further, multiple subclasses can share the same code and are even allowed to update it as per the requirement.
We’ll deal with both cases here
CASE 1: without extending a class method
class Triangles( object ):
count = 0
def __init__( self , name, s1, s2, s3):
self .name = name
self .s1 = s1
self .s2 = s2
self .s3 = s3
Triangles.count + = 1
def setName( self , name):
self .name = name
def setdim( self , s1, s2, s3):
self .s1 = s1
self .s2 = s2
self .s3 = s3
def getcount( self ):
return Triangles.count
def __str__( self ):
return 'Name: ' + self .name + '\nDimensions: ' + str ( self .s1) + ',' + str ( self .s2) + ',' + str ( self .s3)
class Peri(Triangles):
def calculate( self ):
self .pm = 0
self .pm = self .s1 + self .s2 + self .s3
def display( self ):
return self .pm
def main():
p = Peri( 'PQR' , 2 , 3 , 4 )
p.calculate()
print (p.__str__())
print (p.display())
main()
|
Output:
Name: PQR
Dimensions: 2, 3, 4
9
CASE 2: extending a class method
class Triangles( object ):
count = 0
def __init__( self , name, s1, s2, s3):
self .name = name
self .s1 = s1
self .s2 = s2
self .s3 = s3
Triangles.count + = 1
def setName( self , name):
self .name = name
def setdim( self , s1, s2, s3):
self .s1 = s1
self .s2 = s2
self .s3 = s3
def getcount( self ):
return Triangles.count
def display( self ):
return 'Name: ' + self .name + '\nDimensions: ' + str ( self .s1) + ', ' + str ( self .s2) + ', ' + str ( self .s3)
class Peri(Triangles):
def calculate( self ):
self .pm = 0
self .pm = self .s1 + self .s2 + self .s3
def display( self ):
print ( super (Peri, self ).display())
return self .pm
def main():
p = Peri( 'PQR' , 2 , 3 , 4 )
p.calculate()
print (p.display())
main()
|
Output:
Name: PQR
Dimensions: 2, 3, 4
9
The output produced in both cases is the same, the only difference being that the second case makes it easier for other subclasses to inherit the methods and “extend” them as required which as mentioned increases code reusability.