0% found this document useful (0 votes)
11 views13 pages

Polymorphism in Python

Polymorphism in Python allows different objects to respond to the same method name or operator in various ways, enabling code reusability and flexibility. It can be implemented through built-in functions, method overriding, abstract base classes, and operator overloading. The document also outlines different types of polymorphism such as duck typing and provides real-time examples to illustrate its application.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views13 pages

Polymorphism in Python

Polymorphism in Python allows different objects to respond to the same method name or operator in various ways, enabling code reusability and flexibility. It can be implemented through built-in functions, method overriding, abstract base classes, and operator overloading. The document also outlines different types of polymorphism such as duck typing and provides real-time examples to illustrate its application.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Definition & Introduction to Polymorphism in Python

Polymorphism means "many forms." In Python, polymorphism refers to the ability of different objects to
respond to the same method name or operator in different ways.

Key Concept: Same interface, different behavior.

# Example of polymorphism
print(len("Python")) # 6
print(len([1, 2, 3])) # 3

Here, the same len() function behaves differently based on the data type.

How to Implement Polymorphism in Python


1. Built-in Polymorphism (Function Overloading)

Using Python built-in functions that support multiple types:

print(len("Hello")) # 5
print(len([1, 2, 3, 4])) # 4

2. Polymorphism with Functions and Objects

Define a function that can take different types of objects:

class Dog:
def sound(self):
return "Bark"

class Cat:
def sound(self):
return "Meow"

def make_sound(animal):
print(animal.sound())

make_sound(Dog()) # Bark
make_sound(Cat()) # Meow

3. Polymorphism with Inheritance (Method Overriding)


python
CopyEdit
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
for animal in (Dog(), Cat(), Animal()):
animal.speak()

Output:

Dog barks
Cat meows
Animal speaks

4. Polymorphism with Abstract Base Class (abc module)


from abc import ABC, abstractmethod

class Shape(ABC):
@abstractmethod
def area(self):
pass

class Circle(Shape):
def area(self):
return "Area = πr²"

class Square(Shape):
def area(self):
return "Area = side²"

shapes = [Circle(), Square()]


for shape in shapes:
print(shape.area())

Output:

Area = πr²
Area = side²

5. Operator Overloading (Compile-time Polymorphism Simulation)


class Book:
def __init__(self, pages):
self.pages = pages

def __add__(self, other):


return self.pages + other.pages

book1 = Book(100)
book2 = Book(200)
print(book1 + book2) # 300

Types of Polymorphism in Python


Type Description
1. Duck Typing Object type doesn’t matter, behavior does
2. Operator Overloading Redefining operators for user-defined types
3. Method Overriding Child class redefines parent method
4. Function Overloading (Simulated) Can be done using default args or *args

Real-Time Example of Polymorphism


Let’s say we are building a notification system:

class Email:
def send(self):
return "Sending Email"

class SMS:
def send(self):
return "Sending SMS"

class PushNotification:
def send(self):
return "Sending Push Notification"

def notify(service):
print(service.send())

# Polymorphic behavior
notify(Email()) # Sending Email
notify(SMS()) # Sending SMS
notify(PushNotification()) # Sending Push Notification

Summary Table of All Ways


Polymorphism Type Example Real-life Usage
Duck Typing len(), + operator Python built-in behaviors
Method Overriding Base and child class methods OOP designs, reusable components
Abstract Base Class (abc) @abstractmethod usage Enforcing subclass methods
Operator Overloading __add__, __eq__, __lt__ methods Custom behavior for operators
Function Overloading Sim *args, default args Versatile function inputs

In Short:
 Polymorphism allows flexibility and scalability in object-oriented design.
 It helps in writing clean, modular, and extendable code.
 It is used heavily in frameworks, games, GUI apps, etc.

1. What is Polymorphism? (Definition & Introduction)


Definition:
Polymorphism means “many forms”. It allows objects of different classes to be treated as objects of a
common superclass.

Key Idea:
In Python, polymorphism allows different classes to implement methods with the same name. This enables
code reusability, flexibility, and clean code.

2. Types of Polymorphism in Python


Type Description
1. Duck Typing Focus on behavior, not type. "If it walks like a duck and quacks like a
duck..."
2. Operator Overloading Same operator behaves differently with different data types
3. Method Overriding A subclass provides a specific implementation of a method already
defined in its superclass
4. Function Overloading Python does not support it directly, but we can simulate it using default
(Simulated) args or *args

3. Implementation of Each Type with Code

1. Duck Typing Polymorphism


class Dog:
def speak(self):
return "Woof!"

class Cat:
def speak(self):
return "Meow!"

def animal_sound(animal):
print(animal.speak())

dog = Dog()
cat = Cat()

animal_sound(dog) # Output: Woof!


animal_sound(cat) # Output: Meow!

Explanation:
Function animal_sound works with any object that has a speak() method. It doesn’t care about the object’s
class — that’s duck typing.

2. Operator Overloading
class Point:
def __init__(self, x):
self.x = x

def __add__(self, other):


return Point(self.x + other.x)

def __str__(self):
return f"Point({self.x})"

p1 = Point(10)
p2 = Point(20)
print(p1 + p2) # Output: Point(30)

Explanation:
+is overloaded using __add__() to add two Point objects. Normally, + would not work on custom classes.

3. Method Overriding (Runtime Polymorphism)


class Animal:
def speak(self):
return "Some sound"

class Dog(Animal):
def speak(self):
return "Bark"

class Cat(Animal):
def speak(self):
return "Meow"

animals = [Dog(), Cat()]


for a in animals:
print(a.speak())

# Output:
# Bark
# Meow

Explanation:
Each subclass overrides the speak() method. At runtime, Python decides which method to call based on the
object type.

4. Function Overloading (Simulated using Default Arguments)


def greet(name=None):
if name:
print(f"Hello, {name}!")
else:
print("Hello!")

greet() # Output: Hello!


greet("Sriram") # Output: Hello, Sriram!
Explanation:
Python does not support true function overloading. We simulate it using default values or variable-length
arguments.

4. Different Ways to Implement Polymorphism (Summary)


Approach Method Example
Duck Typing Method name reused in different classes speak() in Dog, Cat
Operator Overloading Redefining built-in operators __add__, __sub__
Method Overriding Subclass overrides superclass method speak() in subclass
Function Overloading (Simulated) Use of default arguments / *args greet(name=None)
Abstract Classes Enforce method implementation via abc module

5. Bonus: Using Abstract Base Class for Polymorphism


from abc import ABC, abstractmethod

class Shape(ABC):
@abstractmethod
def area(self):
pass

class Circle(Shape):
def area(self):
return "πr²"

class Square(Shape):
def area(self):
return "side²"

shapes = [Circle(), Square()]


for shape in shapes:
print(shape.area())

# Output:
# πr²
# side²

Explanation:
The Shape class is abstract. Subclasses must implement area(). This enforces polymorphism through
inheritance.

6. Real-time Example of Polymorphism in Python


Let’s say you're developing a payment gateway system:

class Payment:
def pay(self):
return "Processing payment..."
class CreditCard(Payment):
def pay(self):
return "Paid using credit card."

class UPI(Payment):
def pay(self):
return "Paid using UPI."

def make_payment(payment_method):
print(payment_method.pay())

make_payment(CreditCard()) # Output: Paid using credit card.


make_payment(UPI()) # Output: Paid using UPI.

7. Summary Table
Concept Description Example
Duck Typing Same method name, different classes speak() in Dog, Cat
Operator Overloading Custom behavior for operators __add__ in Point
Method Overriding Subclass redefines method speak() in Dog overrides Animal
Function Overloading Simulated using default/*args greet(name=None)
Abstract Classes Enforce structure for subclasses via abc module

Top 25 MCQs on Polymorphism in Python

1. What is polymorphism in Python?

A) Creating many variables


B) Having multiple functions in a class
C) The ability to use a common interface for different data types
D) Using many classes in a program

Answer: C
Explanation: Polymorphism means using a single interface to represent different data types.

2. Which concept allows function names to be reused for different types in Python?

A) Encapsulation
B) Inheritance
C) Polymorphism
D) Abstraction
Answer: C
Explanation: Polymorphism allows reuse of method names with different implementations.

3. Which of the following best illustrates duck typing in Python?

A) Method Overloading
B) Operator Overloading
C) Having different classes implement the same method name
D) Using @property decorators

Answer: C
Explanation: Duck typing is based on behavior rather than class — "If it quacks like a duck..."

4. What is operator overloading in Python?

A) Overriding functions
B) Using more operators
C) Defining custom behavior for operators like +, *, etc.
D) Multiplying operators

Answer: C
Explanation: Operator overloading allows customizing operator behavior using special methods like
__add__().

5. Which method is used to overload the '+' operator?

A) plus
B) add
C) add()
D) operator_add()

Answer: B
Explanation: __add__() is the special method used to define custom addition behavior.

6. Which of the following is NOT a type of polymorphism in Python?

A) Duck Typing
B) Compile-time Polymorphism
C) Run-time Polymorphism
D) Static Typing

Answer: D
Explanation: Python uses dynamic typing. Static typing is not related to polymorphism.
7. Which Python concept allows one method to perform different tasks based on the object?

A) Function overloading
B) Method overriding
C) Encapsulation
D) Constructor chaining

Answer: B
Explanation: Method overriding is when a subclass redefines a method of the parent class.

8. How do you implement function overloading in Python?

A) By declaring functions multiple times


B) Using different function names
C) Using default parameters or *args
D) Python does not allow overloading

Answer: C
Explanation: Python doesn't support traditional overloading, but we can simulate it using default or variable
arguments.

9. What will type("hello") == type(5) return?

A) True
B) False
C) Error
D) None

Answer: B
Explanation: "hello" is a str, and 5 is an int, so types are different.

10. Which of these is an example of polymorphism in Python?


class Cat:
def sound(self):
return "Meow"

class Dog:
def sound(self):
return "Bark"

A) No polymorphism
B) Function overloading
C) Duck typing polymorphism
D) Static polymorphism

Answer: C
Explanation: Both classes use the same method name sound() — this is duck typing.

11. What does @abstractmethod in Python support?

A) Encapsulation
B) Abstraction only
C) Method overriding
D) Polymorphism via interfaces

Answer: D
Explanation: Abstract methods enforce polymorphism by requiring subclasses to implement the method.

12. Which module is used for abstract classes in Python?

A) abstract
B) interfaces
C) abc
D) abs

Answer: C
Explanation: The abc module (Abstract Base Classes) is used for defining abstract classes.

13. What happens if a subclass doesn’t implement an abstract method?

A) It works normally
B) Raises a TypeError
C) Skips execution
D) Automatically creates a method

Answer: B
Explanation: If an abstract method isn't implemented in a subclass, it raises TypeError.

14. What is the output of this?


print(1 + 2)
print("1" + "2")

A) 3 and 3
B) Error
C) 3 and 12
D) 12 and 3

Answer: C
Explanation: + adds numbers and concatenates strings — this is operator overloading.

15. Which concept does the above example demonstrate?

A) Duck typing
B) Operator overloading
C) Method overriding
D) Inheritance

Answer: B

16. What is the key advantage of polymorphism?

A) Less memory
B) More security
C) Code flexibility and reusability
D) Faster execution

Answer: C

17. Which keyword is used to define abstract methods in Python?

A) virtual
B) abstract
C) @abstractmethod
D) override

Answer: C

18. Polymorphism is achieved through:

A) Inheritance and Interfaces


B) Variables only
C) Loops
D) Arrays

Answer: A
19. Which method is used to define behavior for len() in custom classes?

A) len
B) length
C) length
D) get_length

Answer: A
Explanation: __len__() defines length behavior.

20. Polymorphism allows methods to behave differently based on:

A) Input type
B) Loop count
C) Variable names
D) Program version

Answer: A

21. What is method overloading in Python?

A) Same method name with different parameters


B) Different method names with same logic
C) Using lambda functions
D) Not supported

Answer: A
Explanation: Though not native, simulated using default/*args.

22. In method overriding, method resolution happens during:

A) Compile time
B) Run time
C) Installation
D) Declaration

Answer: B

23. __str__() is used to:

A) Convert to string
B) Overload print behavior
C) Create class name
D) Inherit from parent

Answer: B

24. Which is TRUE for operator overloading?

A) Only integers can be overloaded


B) You can't override built-in types
C) Special methods like __add__ are used
D) It works only in C++, not Python

Answer: C

25. Which of these is not a dunder (magic) method for overloading?

A) __eq__()
B) __gt__()
C) __hello__()
D) __mul__()

Answer: C
Explanation: __hello__ is not a valid dunder method for overloading.

You might also like