B.Tech Students: Apply for Live Programming Internship C, C++, Java, Python ,Web page Designing, PHP Polymorphism in Python | LiveCodeProgramming

Polymorphism in Python

Polymorphism means "many forms". In Python, polymorphism allows functions or methods to behave differently based on the object calling them. It is a key feature of Object-Oriented Programming that allows for flexibility and code reuse.

Polymorphism का मतलब है "अनेक रूप"। Python में polymorphism हमें functions या methods को object के अनुसार अलग तरह से behave करने की अनुमति देता है। यह OOP का एक important feature है जिससे flexibility और code reuse मिलता है।

Types of Polymorphism in Python

  • Duck Typing - Object's type doesn't matter as long as it has the required method.
  • Operator Overloading - Use operators like +, * for custom behavior.
  • Method Overriding - Child class overrides parent class method.
  • Duck Typing - Object का type मायने नहीं रखता, बस उसमें required method होना चाहिए।
  • Operator Overloading - Operators जैसे +, * को अपनी class में customize करना।
  • Method Overriding - Child class में parent class के method को overwrite करना।

Example 1: Method Overriding

class Employee:
    def work(self):
        print("Employee works 9 to 5.")

class Manager(Employee):
    def work(self):
        print("Manager manages team and meetings.")

e = Employee()
m = Manager()

e.work()
m.work()

Output:

Employee works 9 to 5.
Manager manages team and meetings.

Example 2: Duck Typing

class Developer:
    def code(self):
        print("Developer writes Python code.")

class Designer:
    def code(self):
        print("Designer writes HTML/CSS code.")

def start_coding(person):
    person.code()

d1 = Developer()
d2 = Designer()

start_coding(d1)
start_coding(d2)

Output:

Developer writes Python code.
Designer writes HTML/CSS code.

Example 3: Operator Overloading

class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

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

e1 = Employee("Aryan", 50000)
e2 = Employee("Naincy", 60000)

print(e1 + e2)

Output:

110000