Polymorphism

Polymorphism 

A fundamental concept in OOP is Polymorphism and a child class can give a complete makeover to a function that it inherited from its parent class. The term Polymorphism refers to the idea of having many forms. Before we get into an example, let’s examine two in-built polymorphous functions that we used.

# The len function computes the length of a string or collection of items

print(len("Verification Master"))
print(len(["Blogs", "Technical", "Writing"]))

This should give us the output as:

The len() function takes an argument and computes it length. The function adapts to the argument and is then used for the type of the argument. Polymorphism refers to a functions ability to take various forms. Let’s see how polymorphism works with the print() function:

print(7 + 14)  # adding integers
print("7" + "14")  # adding strings of numbers
print("abc" + "def" + "ghi")  # adding strings of letters

We can achieve Polymorphism in two ways and those are:

  • Operator Overloading
  • Method Overloading

Operator Overloading

This refers to using an operator in a way that is different that its default usage.

print("aaa" * 3)
print([1, 2, 3] + ["a", "b", "c"])

This prints the letters “aaa” three times. The usual usage of the ‘*’ operator is to multiply numbers or variables referring to numbers, but here we have used the ‘*’ operator in a different way than we are used to. We then combined two lists using the ‘+’ operator.

To use Operator Overloading with classes, we need to use magic methods, and let’s consider an example where we need to add two numbers. We can achieve this using:

class Calculator:

    def __init__(self, input_):
        self.input_ = input_

    def __add__(self, other):
        return self.input_ + other.input_

number_1 = Calculator(3)
number_2 = Calculator(4)

print("Addition gives:", number_1 + number_2)

Here the __add__() function which is a magic method is automatically invoked, because internally when we use the ‘+’ operator we are calling __add__(). Thus, we override this function and, in our class, we add the variables. However, if we try to add these without the magic function it will raise an error saying we cannot add “Calculator” and “Calculator”.

The argument ‘other’ refers to the second value which must also be an instance of the same class, i.e., in this case, ‘4’ of object “number_2”. While it is not necessary for the second instance to have the __add__() function defined, it is necessary for the first instance. This is because behind the scenes the dunder method is called as:

  • number_1.__add__(number_2)

Method Overloading

The concept of Method Overloading is creating a function in the child class, with the same name as a function in the parent class but with more arguments to pass.

class School:

    def __init__(self):
        self.name = "Sunshine School"
        self.staff_count = 50

    def employee_name(self, name=None):
        if name is None:
            print("That was a mistake")
        else:
            print("Welcome to", self.name, "dear", name)


no_name_teacher = School()
no_name_teacher.employee_name()

teacher_1 = School()
teacher_1.employee_name("Rose")

This gives us the output:

Here we created a class “School” with a function that displays a message with the employee’s name. However, it has an argument ‘name’ but is initialized with ‘None’ or uses the default value ‘None’, so that when the function is called without an argument passed with it, it will use ‘None’. 

When we passed the argument “Rose” we get the output as a message which tells us the school’s name and the teacher’s name.

What have we learned?

  • What is Polymorphism?
  • What are some of the built-in functions that use Polymorphism?
  • What are the ways to achieve Polymorphism in Python?
  • How can we overload an operator?
  • What is the use of a magic function?
  • How do we overload a method or function?
  • What is a default argument?
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments