Loading...

Polymorphism in Python with an Example

Polymorphism in Python with an Example

Polymorphism is a programming concept that enables objects of different types to exhibit the same behavior. So, let’s dive into this blog to explore the concept of polymorphism in python, including its various uses in different contexts.

What is polymorphism?

Polymorphism is derived from the Greek words poly (meaning many) and morph (meaning form). It is a concept in object-oriented programming that refers to the ability of different objects to respond to the same method or function call in different ways. This allows for a great deal of flexibility and code reuse. Without the need to know the specific object type, we can utilize the same method or function with different objects.

Polymorphism is the capacity for something to exist in multiple forms. because objects are more than just data structures. This means that if you have a function called my_function, it can be called in different ways depending on how you call it.

They can also contain other classes within themselves and interact with each other through inheritance hierarchies.

Polymorphism in python and its importance

Polymorphism occurs when the same syntax has different meanings in different situations. In Python, we can implement this concept through inheritance, method overloading, and operator overloading. These techniques enable us to define methods or operators that can be used with various types of objects without the need to know the specific object type. Polymorphism allows us to write flexible code that can be used in multiple situations, which makes it easier to manage and maintain complex systems.

Let’s consider a situation where there was a way for us to create an object which would represent all of our data about users on our website (i.e., their name, age and email address). This object should have methods such as getName(), getAge() etc. We could then call these methods on each individual user when they log into our site. So we could display their information quickly without having them retype everything every time to access their account details.

Polymorphism with Function and Objects

One way to achieve polymorphism in Python is by defining functions. We can use these functions with different types of objects. Here is an example of this in action:

class Shape: def __init__(self, name): self.name = name class Circle(Shape): def __init__(self, name, radius): super().__init__(name) self.radius = radius class Rectangle(Shape): def __init__(self, name, width, height): super().__init__(name) self.width = width self.height = height def calculate_area(shape): if isinstance(shape, Circle): return shape.radius ** 2 * 3.14 elif isinstance(shape, Rectangle): return shape.width * shape.height circle = Circle("Circle", 10) rectangle = Rectangle("Rectangle", 20, 30) print(calculate_area(circle)) print(calculate_area(rectangle))
Code language: Python (python)

Output

314.0 600
Code language: Python (python)

In this program, we have defined a Shape class and two derived classes, Circle and Rectangle. We have also defined a calculate_area() function that takes a shape object as an argument and calculates the area using the appropriate method. When we call this function with a Circle object or a Rectangle object, it calculates the area accordingly, without needing to know exactly what type of object it is being used with.

Polymorphism with Class Methods

In a class, methods are functions that we define inside the class body to define the behavior of instances of the class. We can call methods with polymorphism without creating an instance of the class.

Classes are another way to achieve polymorphism in Python. You can define derived class that will override the base class.

class Shape: def area(self): pass class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return self.radius ** 2 * 3.14 class Rectangle(Shape): def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height class Triangle(Shape): def __init__(self, base, height): self.base = base self.height = height def area(self): return self.base * self.height / 2 p = Circle(4) q = Rectangle(4,5) r = Triangle(5,8) print(p.area()) print(q.area()) print(r.area())
Code language: Python (python)

Output

50.24 20 20.0
Code language: Python (python)

In this code, the Shape class defines an area() method that does nothing. This method is then overridden in the derived classes Circle, Rectangle, and Triangle, to provide the appropriate implementation for each type of shape.

Polymorphism With Inheritance

In Python, we can achieve polymorphism with inheritance by defining methods in a base class that derived classes can override.

Through Inheritance, multiple versions of the same class (derived classes) can be created based on the original class (base class). Let me show you an example to make it clear:

class Animal: def make_sound(self): print("Some generic animal sound") class Dog(Animal): def make_sound(self): print("Bark") def eat(self): print("Bone") class Cat(Animal): def make_sound(self): print("Meow") def eat(self): print("Fish") dog = Dog() cat = Cat() dog.make_sound() cat.make_sound() dog.eat() cat.eat()
Code language: Python (python)

Output

Bark Meow Bone Fish
Code language: Python (python)

Polymorphism In Built-in Methods

You can implement polymorphism using the built-in methods in Python as well. Let’s move to see an example of this situation:

class Person: def __init__(self, name, age): self.name = name self.age = age class Employee(Person): def __init__(self, name, age, employee_id): super().__init__(name, age) self.employee_id = employee_id person = Person("John", 30) employee = Employee("Jane", 35, "E123") print(str(person)) print(str(employee))
Code language: Python (python)

Output

<__main__.Person object at 0x7fb917830d90> <__main__.Employee object at 0x7fb9177cf0a0>
Code language: Python (python)

In the above example, we have defined a Person class and an Employee class is a derived class of the Person class. When we try to print an instance of these classes using the str() function. Then, it returns a string representation of the object. However, the default string representation of an object is not very informative. So, we can override the __str__() or __repr__()method in our classes to provide a more meaningful representation.

class Person: def __init__(self, name, age): self.name = name self.age = age def __repr__(self): return f'Person(name={self.name}, age={self.age})' class Employee(Person): def __init__(self, name, age, employee_id): super().__init__(name, age) self.employee_id = employee_id def __str__(self): return f"Employee({self.name} (ID: {self.employee_id}) is {self.age} years old)" person = Person("John", 30) employee = Employee("Jane", 35, "E123") print(str(person)) print(str(employee))
Code language: Python (python)

Output

Person(name=John, age=30) Employee(Jane (ID: E123) is 35 years old)
Code language: Python (python)

Here are additional examples of built-in methods in Python that can be used with multiple types of objects and therefore demonstrate polymorphism.

  1. len() function: The len() function returns the length of an object, which can be a string, list, tuple, or another sequence type. You can use the len() function with multiple types of objects, and it will return the appropriate length for each type.
  2. str() function: The str() function give output a string version of an object. You can use the str() function with multiple types of objects, and it will return the appropriate string representation for each type.
  3. sum() function: The sum() function returns the sum of a sequence of numbers. You can use the sum() function with multiple types of objects, as long as they are sequences of numbers.
print(len("hello")) print(len([1, 2, 3])) print(len((4, 5, 6))) print(str(123)) print(str([1, 2, 3])) print(str((4, 5, 6))) print(sum([1, 2, 3])) print(sum((4, 5, 6)))
Code language: Python (python)

Output

5 3 3 123 [1 2 3] (4 5 6) 6 15
Code language: Python (python)

Operator overloading in Python

Overloading is a feature of Python. It allows us to define methods with the same name but different argument lists.

Operator overloading in Python allows us to specify how built-in operators, such as +, -, *, and / should behave when used with objects of a certain class. This can be achieved by defining special methods in the class, such as __add__(), __sub__(), __mul__(), and __truediv__().Let me show you an example:

class Vector: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Vector(self.x + other.x, self.y + other.y) def __sub__(self, other): return Vector(self.x - other.x, self.y - other.y) def __mul__(self, other): return Vector(self.x * other, self.y * other) def __truediv__(self, other): return Vector(self.x / other, self.y / other) def __str__(self): return f"({self.x}, {self.y})" v1 = Vector(2, 3) v2 = Vector(5, 7) print(v1 + v2) print(v1 - v2) print(v1 * 2) print(v1 / 2)
Code language: Python (python)

Output

(7, 10) (-3, -4) (4, 6) (1.0, 1.5)
Code language: Python (python)

In this code, we have defined a Vector class that represents a 2D vector. We have also defined the __add__(), __sub__(), __mul__(), and __truediv__() methods to provide the desired behavior for the +, -, *, and / operators when used with Vector objects. Now when we use these operators with Vector objects, they are applied elementwise, resulting in a new Vector object. We have also defined the __str__() method to provide a more meaningful representation of the object when it is printed.

Conclusion

In the summary, we saw how to use polymorphism in Python. The main benefit of polymorphism is that it allows us to write code that is more generic. Meaning that it works on many different types of objects and has less chance of failing or producing incorrect results.

FAQs

What is the concept of polymorphism?

Polymorphism is a concept in computer science that refers to the ability of a piece of code to work with multiple different types of data. We achieve this by writing code that is flexible enough to handle various data types, rather than being specific to one particular type.

What does polymorphism mean?

Polymorphism enables us to use a single piece of code with multiple types of objects.

How does Python polymorphism work?

There are several ways to achieve polymorphism in Python:

  1. Using inheritance and method overloading: They can be used to create a base class with a method that can be customized in derived classes. When the method is called on an object of a derived class, the version of the method defined in that class will be executed. This allows for polymorphism.
  2. Using built-in methods: In python, built-in methods are also used for polymorphism.
  3. Using the isinstance() function: You can use the isinstance() function to check the type of an object at runtime and then execute different codes depending on the type.

Why do we use polymorphism?

Polymorphism allows us to write code that is flexible and adaptable, which can make it more efficient and easier to understand. Using polymorphism can help us avoid the need to write separate code for each data type we want to work with, making our code more concise and easier to maintain.

We use polymorphism for what?

We use polymorphism to make our code easier to understand and maintain. because it allows us to write code that is more abstract and general-purpose.

Sharing is caring

Did you like what Srishti Kumari wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far