You are on page 1of 3

Polymorphism comes from the Greek words Poly and morphism which means

having many forms. It is an important feature in Python that allows us to define


methods in the child class with the same name as defined in their parent class.

There are two types of polymorphism


 Overloading
 Overriding

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")

class Quadrilateral (Polygon):


def sides(self):
print("A quadrilateral has 4 sides")
class Triangle(Polygon):
def sides(self):
print("A triangle has 3 sides ")

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

Encapsulation is one of the fundamental concepts in object-oriented


programming (OOP). It puts restrictions on accessing variables and
methods directly to prevent accidental modification of data.

A class variable that should not directly be accessed should be


prefixed with double underscore.

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

person = Person('Jillian', 19)


person.setAge(21)
person.getAge()

Private methods start with two underscores and are accessible only in
their own class. The method can be called using
person._Person__display()

You might also like