Object Oriented

Polymorphism

Python

 

Polymorphism

Python 2.7
class Person:
  def __init__(self, name):
    self.name = name
  
  def getInfo(self):
    return 'name: ' + self.name



class Teacher(Person):
  def __init__(self, name, salary):
    Person.__init__(self, name);
    self.salary = salary
  
  def getInfo(self):
    return 'name: ' + self.name + \
      ', salary: ' + str(self.salary)


class Student(Person):
  def __init__(self, name, gpa):
    Person.__init__(self, name)
    self.gpa = gpa
  
  def getInfo(self):
    return 'name: ' + self.name + \
      ', gpa: ' + self.gpa

Python in design is not type-safe, and natively does not have a concept of interfaces or contracts, but we can create the effects of Polymorphism.

As we showed in Interface topic You can mimic Interfaces and Abstract Classes using abc module and force their subclasses to implement these abstract methods.

Here, if we have a shuffle of teacher and student objects inside an array, you can iterate through them and call the getInfo regardless of those object types.

people = [
  Student('Bob', 'B+'),
  Teacher('Alice', 80000),
  Student('Emma', 'A'),
  Student('Liam', 'B')
]

for i in range(len(people)):
  person = people[i]
  print(person.getInfo())

The sample code above will print info of each person on the screen:

name: Bob, gpa: B+
name: Alice, salary: 80000
name: Emma, gpa: A
name: Liam', gpa: B