Wat is Polymorphism In Python
Answers
Explanation:
In literal sense, Polymorphism means the ability to take various forms. In Python, Polymorphism allows us to define methods in the child class with the same name as defined in their parent class. As we know, a child class inherits all the methods from the parent class.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Rectangle:
def __int__(self, color, filled, width, length):
self.__color = color
self.__filled = filled
self.__width = width
self.__length = length
def get_color(self):
return self.__color
def set_color(self, color):
return self.__color = color
def is_filled(self):
return self.__filled
def set_filled(self, filled):
return self.__filled
def get_area():
return self.__width * self.__length
class Circle:
def __int__(self, color, filled, radius):
self.__color = color
self.__filled = filled
self.__radius = radius
def get_color(self):
return self.__color
def set_color(self, color):
return self.__color = color
def is_filled(self):
return self.__filled
def set_filled(self, filled):
return self.__filled
def get_area(self):
return math.pi * self.__radius ** 2
Did you notice the amount of duplicate code we are writing?
Both classes share the same __color and __filled attribute as well as their getter and setter methods. To make the situation worse, If we want to update how any of these methods work, then we would have to visit each class one by one to make the necessary changes. By using inheritance, we can abstract out common properties to a general Shape class (parent class) and then we can create child classes such as Rectangle, Triangle and Circle that inherits from the Shape class. A child class inherits all the attributes and methods from its parent class, but it can also add attributes and methods of its own.
To create a child class based upon the parent class we use the following syntax:
1
2
3
4
5
6
7
8
9
class ParentClass:
# body of ParentClass
# method1
# method2
class ChildClass(ParentClass):
# body of ChildClass
# method 1
# method 2
In Object-Oriented lingo, when a class c2 inherits from a class c1, we say class c2 extends class c1 or class c2 is derived from class c1.
The following program demonstrates inheritance in action. It creates a class named Shape, which contains attributes and methods common to all shapes, then it creates two child classes Rectangle and Triangle which contains attributes and methods specific to them only.