Wednesday, August 04, 2021

Python: Polymorphism

Python: Polymorphism

A polymorphism in object orinted programming means a same function have more than 1 implementation.

An example of polymorphism in Python:

  > 9*3 ⇒ 27
  > '9'*3 ⇒ 999
  

You can define a multiple function:

  > multiple(9, 3)
  > multiple('9', 3)
  

Different variable type in the parameter produce different output.

Polymorphism: Breathing


class Human(object):
    def breathing(self):
        print('use lungs')

class Fish(object):
    def breathing(self):
        print('use gills')

def breathing(o):
    o.breathing()

alan= Human()
wanna= Fish()
breathing(alan)
breathing(wanna)
⇒ 
use lungs
use gills
  

Another coding:

for o in (alan,wanna):
    breathing(o)
    

No comments:

Post a Comment