Professional Documents
Culture Documents
Polymorphism Comes From The Greek Words Poly and Morphism Which Means Having Many Forms
Polymorphism Comes From The Greek Words Poly and Morphism Which Means Having Many Forms
Overloading: Overloading occurs when two or more methods in one class have the same method name
but different parameters.
class Square:
def __init__(self, side):
self.side = side
def calculate_area(self):
return self.side * self.side
class Rectangle:
def __init__(self, leng, wid):
self.leng = leng
self.wid = wid
def calculate_area(self):
return self.leng * self.wid
sq = Square(5)
rec = Rectangle(5,7)
print("Area of square: ", sq.calculate_area())
print("Area of Rectangle: ", rec.calculate_area())
Output:
Area of square: 25
Area of Rectangle: 35
Overriding: Overriding means having two methods with the same method name and parameters (i.e.,
method signature). One of the methods is in the parent class and the other is in the child class.
Class Polygon:
def intro(self):
print("Polygons are 2-dimensional shapes.")
def sides(self):
print("A polygon has sides 3 or more")
obj_polygon = Polygon ()
obj_quadrilateral = Quadrilateral ()
obj_triangle = Triangle ()
obj_polygon.intro()
obj_polygon.sides()
obj_quadrilateral.intro()
obj_quadrilateral.sides()
obj_triangle.intro()
obj_triangle.sides()
Output:
Polygons are 2-dimensional shapes.
A polygon has sides 3 or more
Polygons are 2-dimensional shapes.
A quadrilateral has 4 sides
Polygons are 2-dimensional shapes.
A triangle has 3 sides
class Person:
def __init__(self, name, age=0):
self.name = name
self.__age = age
def display(self):
print(self.name)
print(self.__age)
To access and change private variables, accessor (getter) methods and
mutator (setter methods) should be used which are part of the class.
class Person:
def __init__(self, name, age=0):
self.name = name
self.__age = age
def __display(self):
print(self.name)
print(self.__age)
def getAge(self):
print(self.__age)
def setAge(self, age):
self.__age = age
Private methods start with two underscores and are accessible only in
their own class. The method can be called using
person._Person__display()