Wednesday, May 25, 2016

An Introduction to Object Oriented Programming in Python - Part 8

Polymorphism in Python OOP

Make sure you read Part 1, Part 2, Part 3, Part 4Part 5 Part 6 and Part 7 before you continue reading...

In practical terms, polymorphism means that if class B inherits from class A, it doesn’t have to inherit everything about class A; it can do some of the things that class A does differently (wikipedia).

Polymorphism is based on the greek words Poly (many) and morphism (forms).

Lets demonstrate polymorphism from the previous Part 7:-

Here we have two class: Cars and Bikes. Both are objects considered as Vehicles. The Cars class and the Bikes class inherit the Vehicles class. They have a activateHorn() method, which gives different output for them.

class Vehicles:
   def __init__(self, brand=""):
      self.brand = brand

   def activateHorn(self):
      pass

class Cars(Vehicles):
   def activateHorn(self):
      print "Cars Horn is: Poooooooorh!"

class Bikes(Vehicles):
   def activateHorn(self):
      print "Bikes Horn is: Piiiiiiiiih!"

a = Vehicles()
a.activateHorn()

c = Cars("Toyota")
c.activateHorn()

d = Bikes("BMX")
d.activateHorn()


If the above example isn't clear, here is another using animal objects (without inheritance).

We create two classes:  Goat and Dog, both  can make a distinct sound.  We then make two instances and call their action using the same method.

class Goat:
    def sound(self):
        print "Meeh, meeh"
 
class Dog:
    def sound(self):
        print "Woof, woof!"
 
def makeSound(animalType):
    animalType.sound()
 
 
goatObj = Goat()
dogObj = Dog()
 
makeSound(goatObj)
makeSound(dogObj)


That is the basic of polymorphism (object coming in many types or forms).

Reference Materials are here

No comments:

Post a Comment