Home » Posts tagged 'Polymorphism in Python'

Tag Archives: Polymorphism in Python

Newly Updated Posts

Python Polymorphism

Polymorphism is one of the fundamental principles of object-oriented programming (OOP) and is supported by the Python programming language. It allows objects of different classes to be treated as objects of a common superclass. Polymorphism enables you to write code that can work with objects of multiple types, providing flexibility and code reusability.

In Python, polymorphism is typically achieved through method overriding and method overloading.

  1. Method Overriding: Method overriding occurs when a subclass defines a method that is already present in its superclass with the same name and signature. The overridden method in the subclass replaces the implementation of the method in the superclass, allowing the subclass to provide its own implementation.

Here’s an example:

class Animal:
    def sound(self):
        print("Animal makes a sound")


class Cat(Animal):
    def sound(self):
        print("Cat meows")


class Dog(Animal):
    def sound(self):
        print("Dog barks")


animals = [Cat(), Dog()]

for animal in animals:
    animal.sound()

Output:
Cat meows
Dog barks

In the example above, the Animal class has a method called sound(). The Cat and Dog classes inherit from the Animal class and override the sound() method with their own implementations. When we iterate over the animals list and call the sound() method, the appropriate implementation is called based on the actual type of the object.

  1. Method Overloading (via Function Overloading): Method overloading refers to defining multiple methods with the same name but different parameters or argument types. However, Python does not support method overloading in the same way as languages like Java or C++. Instead, you can achieve a similar effect using default arguments or variable-length arguments.

Here’s an example:

class MathOperations:
    def add(self, a, b):
        return a + b

    def add(self, a, b, c):
        return a + b + c


math_ops = MathOperations()
print(math_ops.add(2, 3))       # This will raise an error

# Using variable-length arguments
class MathOperations:
    def add(self, *args):
        return sum(args)


math_ops = MathOperations()
print(math_ops.add(2, 3))       # Output: 5
print(math_ops.add(2, 3, 4))    # Output: 9

In the first example, attempting to call math_ops.add(2, 3) will raise an error because the add() method with two arguments is overwritten by the method with three arguments.

To work around this limitation, you can use variable-length arguments (*args) to define a single add() method that can accept any number of arguments. Inside the method, you can then perform the desired operation, such as summing all the arguments.

Polymorphism allows you to write code that can work with objects of different types, as long as they share a common interface or superclass. This flexibility simplifies code design, promotes code reuse, and makes it easier to extend your programs in the future.

Python OOPs Concepts

Python supports object-oriented programming (OOP) concepts. Here are the main concepts in Python OOP:

1. Classes and Objects: A class is a blueprint for creating objects, while an object is an instance of a class. Classes define the properties (attributes) and behaviors (methods) that objects of that class can have.

2. Encapsulation: Encapsulation is the process of bundling data and methods within a class, hiding the internal details and protecting the data from direct manipulation. It is achieved by using access modifiers like public, private, and protected.

3. Inheritance: Inheritance allows a class to inherit properties and methods from another class. The class being inherited from is called the base class or superclass, and the class inheriting from it is called the derived class or subclass. The derived class can extend or override the functionality of the base class.

4. Polymorphism: Polymorphism allows objects of different classes to be treated as objects of a common superclass. It enables methods with the same name to be called on different objects, and the appropriate method is executed based on the object’s type. Polymorphism can be achieved through method overriding and method overloading.

5. Method Overriding: Method overriding occurs when a derived class defines a method with the same name as a method in its superclass. The derived class’s method overrides the implementation of the base class method, allowing the derived class to provide its own implementation.

6. Method Overloading: Method overloading enables a class to have multiple methods with the same name but different parameters. Python does not support method overloading directly, but you can achieve similar behavior using default argument values or variable-length argument lists.

7. Abstraction: Abstraction refers to the process of hiding complex implementation details and providing a simplified interface. It allows the user to interact with the objects without needing to know the underlying complexity. Abstract classes and interfaces are used to achieve abstraction in Python.

8. Composition: Composition is a form of association where one class contains an instance of another class as a member. It allows creating complex objects by combining simpler objects. Composition is often used when the relationship between classes is not a “is-a” relationship (as in inheritance) but rather a “has-a” relationship.

These concepts form the foundation of object-oriented programming in Python. By utilizing these concepts, you can create modular, reusable, and maintainable code that models real-world entities effectively.