Home » Posts tagged 'Python polymorphism'

Tag Archives: Python polymorphism

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.

Class,Object and Members

In this tutorial we will learn Class, Object and Members in Python.

In Python, classes are used to create objects, which are instances of those classes. Classes serve as blueprints or templates for creating objects with similar characteristics and behaviors. Each object created from a class is called an instance or an object of that class.

A class defines the properties (also known as attributes) and behaviors (also known as methods) that objects of that class will have. Attributes are variables that store data, while methods are functions that define the behavior of the class.

Here’s an example of a simple class definition in Python:

class Car:
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

    def start_engine(self):
        print("The engine has started.")

    def drive(self):
        print("The car is being driven.")

    def stop_engine(self):
        print("The engine has stopped.")

In the above example, Car is the class, and make, model, and year are its attributes. The __init__ method is a special method called the constructor, which is executed when an instance of the class is created. It initializes the attributes of the object using the values passed as arguments.

The start_engine, drive, and stop_engine methods are behaviors associated with the Car class. They define the actions that objects of the Car class can perform.

To create an instance of the Car class, you can do the following:

my_car = Car("Toyota", "Camry", 2022)

Here, my_car is an object of the Car class. It has the attributes make (set to “Toyota”), model (set to “Camry”), and year (set to 2022). You can access the attributes and call the methods of the object using dot notation, like this:

print(my_car.make) # Output: Toyota

print(my_car.model) # Output: Camry

print(my_car.year) # Output: 2022

my_car.start_engine() # Output: The engine has started.

my_car.drive() # Output: The car is being driven.

my_car.stop_engine() # Output: The engine has stopped.

In summary, classes define the structure and behavior of objects, while objects are instances of those classes. Members refer to the attributes and methods associated with a class or an object. Attributes store data, and methods define the behaviors or actions that can be performed by the class or object.