0% found this document useful (0 votes)
0 views9 pages

Polymorphism

Polymorphism is a key concept in object-oriented programming that allows a single function or method to exhibit different behaviors based on the object it is acting upon. In Python, it is primarily implemented through method overriding and operator overloading, enabling code reusability, maintainability, and flexibility. While method overloading is not directly supported, it can be simulated using variable arguments.

Uploaded by

faxi.dev06
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views9 pages

Polymorphism

Polymorphism is a key concept in object-oriented programming that allows a single function or method to exhibit different behaviors based on the object it is acting upon. In Python, it is primarily implemented through method overriding and operator overloading, enabling code reusability, maintainability, and flexibility. While method overloading is not directly supported, it can be simulated using variable arguments.

Uploaded by

faxi.dev06
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

polymorphism

Polymorphism ek important concept hai object-oriented programming (OOP) mein, aur Python bhi
ek object-oriented language hai. Polymorphism ka matlab hai "many forms" ya "multiple forms". Iska
mtlb hai ki ek hi function ya method different objects ke liye alag-alag behavior show kar sakta hai.

Polymorphism ko samajhne ke liye 2 main types hain:

Method Overriding

Method Overloading (Although Python mein method overloading ko directly implement nahi kiya ja
sakta)

1. Method Overriding (Runtime Polymorphism):

Ismein ek subclass apne parent class ke method ko override karta hai, yaani ki apne specific behavior
ko define karta hai. Jab hum parent class ka method call karte hain aur subclass usko override kar leta
hai, tab jo behavior perform hota hai wo subclass ka hota hai.

Example:

python

Copy code

class Animal:

def speak(self):

print("Animal speaks")

class Dog(Animal):

def speak(self):

print("Dog barks")

class Cat(Animal):

def speak(self):

print("Cat meows")

# Polymorphism in action:

def animal_sound(animal):

animal.speak()
# Yahan par, dog aur cat ka specific speak method call hoga, depending on the object type

dog = Dog()

cat = Cat()

animal_sound(dog) # Output: Dog barks

animal_sound(cat) # Output: Cat meows

Explanation:

Animal class: Yeh ek base class hai jisme ek speak method hai.

Dog aur Cat classes: Yeh subclasses hain jo speak method ko apne hisaab se override kar rahe hain.

Jab hum animal_sound() function call karte hain aur usme ek Dog ya Cat ka object pass karte hain, to
wo object apna apna speak() method call karega. Yani Dog ka speak() method ya Cat ka speak()
method execute hoga.

Yeh runtime polymorphism hai, kyunki kis method ko call karna hai yeh runtime (execution time) par
decide hota hai, jo object pass ho raha hai uske type ke hisaab se.

2. Method Overloading (Compile-time Polymorphism):

Python mein method overloading directly implement nahi kiya ja sakta, jaise Java ya C++ mein hota
hai. Lekin Python mein ek hi method ko multiple arguments ke saath use kar sakte hain, aur hum
argument ki type ya quantity ke hisaab se behavior change kar sakte hain.

Example (Simulating Overloading):

python

Copy code

class MathOperations:

def add(self, *args): # *args allows multiple arguments

result = 0

for num in args:

result += num

return result

# Polymorphism simulation:

math = MathOperations()

print(math.add(5)) # Output: 5
print(math.add(5, 10)) # Output: 15

print(math.add(1, 2, 3, 4)) # Output: 10

Explanation:

add method: Humne *args use kiya hai jo multiple arguments ko accept karta hai.

add() method ko alag-alag number of arguments ke saath call kiya gaya hai.

Polymorphism ka example hai ki ek hi add() method ko multiple tariko se use kiya ja raha hai aur uska
behavior arguments ke hisaab se change ho raha hai.

3. Operator Overloading:

Python mein, hum operators ko bhi overload kar sakte hain, jisse ki hum apni custom behavior define
kar sakte hain jab hum operators ka use karte hain.

Example:

python

Copy code

class Point:

def __init__(self, x, y):

self.x = x

self.y = y

# Overloading the '+' operator

def __add__(self, other):

return Point(self.x + other.x, self.y + other.y)

def __repr__(self):

return f"Point({self.x}, {self.y})"

# Creating Point objects

point1 = Point(1, 2)

point2 = Point(3, 4)

# Using overloaded '+' operator

result = point1 + point2


print(result) # Output: Point(4, 6)

Explanation:

__add__ method: Yeh method humne + operator ko overload karne ke liye define kiya hai. Jab hum
point1 + point2 likhte hain, to internally yeh __add__ method call hota hai.

Custom behavior: Jab hum + operator use karte hain, to yeh Point objects ke x aur y coordinates ko
add karta hai.

Polymorphism ka FAYDA:

Code Reusability: Ek method ko alag-alag objects ke liye use kar sakte hain. Jaise upar ke examples
mein animal_sound() function ko hum Dog aur Cat objects ke liye reuse kar rahe hain.

Maintainability: Agar aapko koi behavior change karna ho, to aapko bas subclass ka method change
karna padega. Parent class ko modify karne ki zarurat nahi.

Flexibility: Aapke code ko zyada flexible bana deta hai. Aap alag-alag types ke objects ke saath ek hi
method ya function ko use kar sakte hain.

Summary:

Polymorphism ek powerful concept hai jisse hum ek hi function ya method ko different objects ke
liye different behavior dene ki koshish karte hain.

Python mein Method Overriding aur Operator Overloading jaise features hote hain jo polymorphism
ko implement karte hain.

Isse code ko zyada flexible, reusable aur maintainable banaya ja sakta hai.

Umeed hai ki aapko polymorphism ka concept achhe se samajh aaya hoga! Agar aapko koi aur
clarification chahiye ho, to zarur batayein!

You said:

explain n english also, with proper definations

ChatGPT said:

ChatGPT

Sure! Let's dive into the concept of Polymorphism in Python in detail, starting with the basic
definition, followed by examples, and its benefits.

Definition of Polymorphism:

Polymorphism is one of the fundamental concepts in Object-Oriented Programming (OOP). The word
"Polymorphism" comes from two Greek words: "poly" meaning many, and "morph" meaning forms.
So, polymorphism literally means "many forms".
In simple terms, polymorphism allows objects of different classes to be treated as objects of a
common superclass. The primary benefit of polymorphism is that the same method or function can
behave differently depending on the object that it is acting upon.

Polymorphism can be categorized into two types:

Compile-time Polymorphism (Method Overloading)

Runtime Polymorphism (Method Overriding)

Let’s explore both with examples.

1. Runtime Polymorphism (Method Overriding):

In runtime polymorphism, a subclass provides a specific implementation of a method that is already


defined in its superclass. When a method is called on an object, the subclass version of the method is
executed, not the superclass version.

This is dynamic method resolution, meaning the decision of which method to call happens at
runtime.

Example (Method Overriding):

python

Copy code

class Animal:

def speak(self):

print("Animal speaks")

class Dog(Animal):

def speak(self):

print("Dog barks")

class Cat(Animal):

def speak(self):

print("Cat meows")

# Polymorphism in action
def animal_sound(animal):

animal.speak() # Calls the overridden 'speak' method

# Create instances of Dog and Cat

dog = Dog()

cat = Cat()

# Here, depending on the object passed, the correct method is called

animal_sound(dog) # Output: Dog barks

animal_sound(cat) # Output: Cat meows

Explanation:

Animal class: This is the base class with a speak() method that prints a generic message.

Dog and Cat classes: These are subclasses of Animal. Both override the speak() method to provide
their own specific implementation.

Polymorphism in action: The function animal_sound() calls the speak() method, but it behaves
differently depending on whether it’s a Dog or Cat object.

So, runtime polymorphism allows us to use the same method name but have different behaviors
based on the object type.

2. Compile-time Polymorphism (Method Overloading):

In compile-time polymorphism, methods with the same name can be defined but with different
parameters (i.e., different types or numbers of arguments). However, Python does not support
method overloading directly (like Java or C++).

In Python, you can simulate method overloading by using default parameters or variable-length
argument lists (*args or **kwargs).

Example (Simulating Method Overloading using *args):

python

Copy code

class MathOperations:

def add(self, *args): # *args allows multiple arguments

result = 0
for num in args:

result += num

return result

# Creating an object of MathOperations

math = MathOperations()

# Using the same 'add' method with different number of arguments

print(math.add(5)) # Output: 5

print(math.add(5, 10)) # Output: 15

print(math.add(1, 2, 3, 4)) # Output: 10

Explanation:

add method: The add() method is defined with *args, which allows it to accept any number of
arguments.

Method overloading simulation: You can call the same method (add) with different numbers of
arguments, and it will return the sum accordingly.

In Python, we don't have true compile-time polymorphism, but we can achieve similar functionality
with variable arguments or default parameters.

3. Operator Overloading:

Python also supports operator overloading, which means you can define custom behavior for
operators (like +, -, *, etc.) for objects of a class. This is a form of polymorphism where you can define
how operators work with objects of your custom class.

Example (Operator Overloading):

python

Copy code

class Point:

def __init__(self, x, y):

self.x = x

self.y = y

# Overloading the '+' operator


def __add__(self, other):

return Point(self.x + other.x, self.y + other.y)

def __repr__(self):

return f"Point({self.x}, {self.y})"

# Create Point objects

point1 = Point(1, 2)

point2 = Point(3, 4)

# Using overloaded '+' operator

result = point1 + point2

print(result) # Output: Point(4, 6)

Explanation:

__add__ method: This special method is used to define the behavior of the + operator when used
with objects of the Point class.

Custom behavior for + operator: The + operator adds the x and y coordinates of two Point objects
and returns a new Point object with the result.

Polymorphism: Here, the + operator behaves differently based on the type of object (in this case,
Point objects).

Benefits of Polymorphism:

Code Reusability:

Polymorphism allows us to write generic functions or methods that can work with objects of
different types. This increases code reusability.

For example, the animal_sound() function can work with any object that inherits from Animal,
without needing to change the function's code.

Maintainability:

When you have multiple subclasses, polymorphism allows you to write a single function that works
across different subclasses. If you want to change the behavior of a subclass, you only need to
modify the subclass’s method.

Flexibility:
It makes the code more flexible and easier to extend. For instance, if you want to add new types of
Animal in the future (e.g., Bird), you don't need to change the animal_sound() function. You just add
a new subclass with its own implementation of the speak() method.

Summary:

Polymorphism allows the same method or function to behave differently based on the object that it
is operating upon.

Method Overriding is used to provide different implementations of a method in a subclass, which is


resolved at runtime.

Method Overloading is not natively supported in Python, but can be simulated using variable
arguments (*args).

Operator Overloading allows you to define custom behavior for operators in Python.

Benefits: Polymorphism makes code more flexible, reusable, and maintainable.

Polymorphism is one of the core concepts in OOP that enables you to write cleaner and more
extensible code.

Let me know if you need further clarification or examples!

You might also like