Polymorphism
Polymorphism
Polymorphism
Lesson objectives
• 11.4.2.1 explain the concept of polymorphism with examples
Assessment criteria:
1. develop methods for the class
2. gives an example of polymorphism
What is Polymorphism?
print(len('school')) # 6
print(len([2, 3, 5, 7, 11, 13, 17, 19, 23])) # 9
print(len(('A', 'B', 'C'))) # 3
Other example, operation + (addition). In Python we can add whole
numbers, float numbers, strings, lists, etc.
print(5 + 3) #8
print(2.7 + 3.4) # 6.1
print('Hello, ' + 'world!') # Hello, world!
print([2, 3, 5] + [7, 11, 13]) # [2, 3, 5, 7, 11, 13]
print(len("Scaler Academy"))
print(len(["Python", "PHP", "C++"]))
print(len({"Name": "Rahul", "Address": "Kolkata,India"}))
Output:
14
3
2
Use addition function
print(func_add(5, 3)) #8
print(func_add(2.7, 3.4)) # 6.1
print(func_add('Hello, ', 'world!')) # Hello, world!
print(func_add([2, 3, 5], [7, 11, 13])) # [2, 3, 5, 7, 11, 13]
Polymorphism with Function and Objects
class Tomato(): class Apple():
def type(self):
def type(self):
print("Fruit")
print("Vegetable") def color(self):
def color(self): print("Red")
print("Red") def func(obj):
obj.type()
obj.color()
obj_tomato = Tomato() Output:
obj_apple = Apple() Vegetable
func(obj_tomato) Red
Fruit
func(obj_apple) Red
class T1:
def __init__(self):
self.n = 10
def total(self, a):
return self.n + int(a)
class T2:
def __init__(self):
self.string = 'Hi'
t1 = T1()
t2 = T2()
print(t1.total(35)) # Вывод: 45
print(t2.total(35)) # Вывод: 4
Task1
Create multiple classes with different behavior of the same method
Task 2
Create classes vegetables and fruits with different behavior of the same
method
Task 3
• Create classes dog and cat with different behavior of the same
method