Py16: Polymorphism
Polymorphism is characteristic shown by an object to take more than one form. There are several ways to apply polymorphism concept when writing a program.
The simplest form of polymorphism is by defining a function with default argument. For example, the function below takes three parameters, with third parameter has default value. Default value used by the third parameter if third argument is not provided by user.
def add(a, b,c = 0):
return a + b + c
print(add(34.6,42))
print(add(31,2.4,27))
Output
76.6 60.4
The len() function is an example of built-in function that show polymorphism. They can work on any data types or structures. For example, if string is given it returns number of characters, meanwhile is a list is given, it return number of items in the list.
print(len("teachercuber"))
print(len(["tic","tac","toe", 26]))
Output
12 4
Next, polymorphism is in the inheritance between classes, through method overriding.
class Bird:
def general(self):
print("Most bird can fly")
def size(self):
print("Bird sizes can vary")
class Eagle(Bird):
def size(self):
print("Eagles are big")
class Sparrow(Bird):
def size(self):
print("Sparrow are small")
bird = Bird()
eagle = Eagle()
sparrow = Sparrow()
eagle.general()
bird.size()
eagle.size()
sparrow.size()
Output
Most bird can fly Bird sizes can vary Eagles are big Sparrow are small
Secondly, Polymorphism in class methods. It uses a list of object that has same methods. The list of object is iterated using for loop, which calls the same method for every objects in the list.
class Cat:
def move(self):
print("Cat walk")
def talk(self):
print("Meow")
def eat(self):
print("fish")
class Dog:
def move(self):
print("Dog peddle")
def talk(self):
print("Woof")
def eat(self):
print("Bones")
for pet in (Cat(), Dog()):
pet.move()
pet.talk()
pet.eat()
Output
Cat walk Meow fish Dog peddle Woof Bones
Polymorphism using function. We use a function that takes object as parameter. The function calls the methods belongs to the current object.
class Football:
def players(self):
print("11 players in football game")
def score(self):
print("Unlimited goals")
class Volleyball:
def players(self):
print("Volleyball has 6 players in a team")
def score(self):
print("First to score 25 with two-point margin")
def aFunc(object):
object.players()
object.score()
game1 = Football()
game2 = Volleyball()
aFunc(game1)
aFunc(game2)
Output
11 players in football game Unlimited goals Volleyball has 6 players in a team First to score 25 with two-point margin
Comments
Post a Comment