Polymorphism in Python

In programming, polymorphism refers to an object with the same name but provides different results, depending on the input. This lesson will only cover a basic overview. In the advanced programming world, we never use polymorphism and it has yet to come up in a coding interview. The following examples show that one object called ‘person’ can display the right ‘getDetails’ function output through polymorphism:


class person:
    def __init__(self,name,age):
        self.name = name
        self.age = age
        self.courses = []

        def getDetails(self):
            print("Error: You cannot call details withoout instantiation")

class instructor(person):
    def __init__(self,name,age):
        super().__init__(name, age)
        self.studentsAssigned = 0

    def getDetails(self):
        print("{} has {} students assigned".format(self.name, str(self.studentsAssigned)))

class student(person):
    def __init__(self,name,age):
        super().__init__(name, age)
        self.grades = []
    def getDetails(self):
        print("{} has the following grades: {}".format(self.name, str(self.grades)))     

people = [student(age=20,name="John Doe"), instructor(age=30, name="Obi Wan")]

for person in people:
    person.getDetails()

The key takeaway is that objects were created and stored in a single collection. We did not need to call each reference individually, only one single loop was needed. This is a contrast to having to instantiate a class like student1 = student() and student2 = student(). You would then have to call the get details as student1.getDetails() and student2.getDetails().

1 thought on “Polymorphism in Python”

Leave a Comment