0% found this document useful (0 votes)
3 views41 pages

Polymorphism & Inheritance

The document discusses key concepts of programming in Python, focusing on polymorphism and operator overloading. It explains how polymorphism allows methods to behave differently based on the object type and provides real-life analogies for better understanding. Additionally, it covers inheritance in Python, detailing its types and advantages, alongside practical examples.

Uploaded by

asway933
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)
3 views41 pages

Polymorphism & Inheritance

The document discusses key concepts of programming in Python, focusing on polymorphism and operator overloading. It explains how polymorphism allows methods to behave differently based on the object type and provides real-life analogies for better understanding. Additionally, it covers inheritance in Python, detailing its types and advantages, alongside practical examples.

Uploaded by

asway933
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

Paper: Programming in Python

Paper Code: SEC-154


Unit -3
Prepared By: Dr. Ankita Sharma
Assistant Professor
USICT, GGSIPU

UNIVERSITY SCHOOL OF INFORMATION, COMMUNICATION &


TECHNOLOGY,
GURU GOBIND SINGH INDRAPRASTHA UNIVERSITY.
• polymorphism
• operator overloading
(_eq_, _str_, etc)
AGENDA
Real Life Use Cases

1. Vending Machine Analogy


Imagine a vending machine with one button for
"Dispense".
• If we insert ₹10 and press "Dispense", it gives a small
packet of chips.
• If we insert ₹20 and press "Dispense", it gives a cold
drink.
• If we insert ₹50, same "Dispense" gives a combo snack.
Same interface (button), but behavior changes based on
input (object/type). This models polymorphism — one
method (Dispense) works differently for different
"contexts".
Real Life Use Cases

2. Teacher Asking "Introduce Yourself" in Class

• Teacher (me) says: "Introduce yourself" to:

• A student – says name, grade, favorite subject.

• A teacher – says name, department, research area.

• A principal – says name, position, vision statement.


Same question (method), but the response depends on who
is being asked (object type).
Real Life Use Cases

3. Drawing Shapes on a Whiteboard

We give a command: draw()

• If it's a circle, it draws a round shape.

• If it's a rectangle, it draws a box.

• If it's a triangle, it draws three sides.

The same method call (draw()) gives different results


based on the object (shape).
Polymorphism

• It's derived from the Greek words poly (many) and


morph (form), meaning "many forms".

• Polymorphism is an OOP concept where the same


function or method name can be used for different types
of objects, and each object responds differently based
on its own class implementation.

• Polymorphism is like giving the same command to


different people or things and watching how each does
it in their own unique way.
Polymorphism

• Polymorphism is a core concept in object-oriented


programming (OOP) that refers to the ability of
different objects to respond to the same method or
function call in a way that is specific to their type.

• Polymorphism is the ability of a message or method call


to be processed in more than one form.

• In Python, polymorphism allows methods in


different classes to have the same name but behave
differently depending on the object calling them.
Advantages of Polymorphism

1. Code Reusability
Polymorphism allows us to write generic code that can
work with different data types or classes, reducing
duplication.
def animal_sound(animal):
print([Link]())
We don't need to write separate functions for Dog, Cat, etc.

2. Flexibility and Extensibility


We can add new classes (without changing existing code
that uses polymorphism.
Advantages of Polymorphism

3. Improves Readability and Maintainability


Code is cleaner, easier to understand, and changes are
more localized when new behaviors are introduced.

4. Supports Dynamic Method Resolution


Python determines the method to invoke at runtime,
allowing for dynamic and flexible behavior.
Types

• Polymorphism in Python is primarily achieved through


method overriding (runtime polymorphism)

• and method overloading (though Python doesn't


support method overloading in the traditional sense).
1. Runtime Polymorphism
(Method Overriding)
• Runtime Polymorphism is when a method in a subclass
overrides the method in the parent class to provide
specific behavior.
• This allows the same method to behave differently
depending on the object that calls it.
class Animal:
def sound(self):
print("Animal makes a sound")
class Dog(Animal):
def sound(self): # Method overriding
print("Dog barks")
class Cat(Animal):
def sound(self): # Method overriding
print("Cat meows")
# Create objects
dog = Dog()
cat = Cat()
# Polymorphism in action
animals = [dog, cat]
for animal in animals:
[Link]() # Calls the overridden method based on
the object type
2. Compile-time Polymorphism
(Method Overloading)

• Compile-time Polymorphism refers to using different


method signatures in the same class (same method name
with different parameter lists).
• In languages like C++ or Java, method overloading is
directly supported.
• However, in Python, method overloading is achieved
through variable arguments or by checking the type of
arguments within a method.
What is Operator Overloading?

• Operator Overloading is a feature in Python that allows


user-defined classes to redefine the behavior of built-in
operators (like +, ==, >, etc.) for their own objects,
using special methods (also known as dunder methods).

• Operator overloading allows custom classes to define or


modify the behavior of standard Python operators (like
+, -, ==, etc.) for their own objects.
What is Operator Overloading?

Python provides special methods (magic/dunder methods)


that you can implement to customize the behavior of these
operators. Some commonly used methods are:

• __eq__(self, other) – Equality (==)

• __str__(self) – String representation (str())

• __add__(self, other) – Addition (+)

• __lt__(self, other) – Less than (<)


Real-Life Use Cases and
Analogies
1. String Concatenation vs. Integer Addition
• "Ankita" + " Sharma" → "Ankita Sharma" (joins
strings)
• 10 + 20 → 30 (adds numbers)
• Same +, different behavior = Operator Overloading

2. Comparing Students (Overloading ==)


• If two Student objects have the same roll number, we
define them as equal using __eq__().
Advantages of Operator
Overloading
1. Improves Readability
Objects can be interacted with in a natural, intuitive way
using operators.
2. Supports Polymorphism
Operators behave differently depending on object type
(e.g., + can add numbers, join strings, or merge custom
objects).
3. Enhances Code Reusability
Same operator logic can be reused for multiple objects of
the class.
Example: __eq__ and __str__
class Student:
def __init__(self, name, roll):
[Link] = name
[Link] = roll
def __eq__(self, other):
return [Link] == [Link]
def __str__(self):
return f"Student Name: {[Link]}, Roll No:
{[Link]}"
s1 = Student("Ankita", 101)
s2 = Student("Riya", 101)
print(s1 == s2) # True – because roll numbers are same
print(s1)# Uses __str__: "Student Name: Ankita, Roll
No: 101"
Inheritance In
Python
AGENDA
Inheritance
Inheritance is a fundamental concept in Object-Oriented
Programming (OOP) that allows a class (child or derived
class) to inherit attributes and methods from another class
(parent or base class).

Real-life Analogy
Think of Inheritance like real-life family traits:
• A child inherits genes from parents.
• We might have your father’s nose and mother’s eyes.
In Python, a class can inherit methods and attributes from a
base class the same way.
Advantages of Inheritance
1. Code Reusability: Avoids rewriting the same code.

2. Modularity: Enhances maintainability.

3. Extensibility: New features can be added easily by


extending existing classes.

4. DRY Principle: Helps in following Don’t Repeat


Yourself.
Types of Inheritance
Description
Type

One child class inherits from one parent class


Single Inheritance

A child class inherits from multiple parent classes


Multiple Inheritance

A class inherits from a class which itself is


Multilevel Inheritance inherited from another class

Multiple child classes inherit from a single parent


Hierarchical Inheritance class

Combination of more than one type of inheritance


Hybrid Inheritance
1. Single Inheritance
One child class inherits from one parent class.
class Animal:
def eat(self):
print("This animal eats food.")

class Dog(Animal): # Inheriting from Animal


def bark(self):
print("The dog barks.")

# Creating object
d = Dog()
[Link]() # Inherited method
[Link]() # Own method
2. Multilevel Inheritance
A class inherits from a child class, which itself inherits
from a parent class.
class Grandparent:
def speak(self):
print("Grandparent speaks.")
class Parent(Grandparent): # Inheriting from Grandparent
def walk(self):
print("Parent walks.")
class Child(Parent): # Inheriting from Parent
def play(self):
print("Child plays.")
c = Child()
[Link]() # From Grandparent
[Link]() # From Parent
[Link]() # Own method
3. Multiple Inheritance
A class inherits from more than one parent class.
class Mother:
def cook(self):
print("Mother cooks.")
class Father:
def drive(self):
print("Father drives.")
class Child(Mother, Father): # Inheriting from both
def study(self):
print("Child studies.")
c = Child()
[Link]() # From Mother
[Link]() # From Father
[Link]() # Own method
4. Hierarchical Inheritance
Multiple child classes inherit from the same parent class.
class Teacher:
def teach(self):
print("Teacher teaches.")
class MathTeacher(Teacher):
def solve_equations(self):
print("Solving math equations.")
class PhysicsTeacher(Teacher):
def explain_laws(self):
print("Explaining physics laws.")
m = MathTeacher()
p = PhysicsTeacher()
[Link]()
m.solve_equations()
[Link]()
p.explain_laws()
5. Hybrid Inheritance
A combination of more than one type of inheritance
(usually multiple + multilevel).
class Person:
def info(self):
print("This is a person.")
class Student(Person):
def study(self):
print("Student studies.")
class Teacher(Person):
def teach(self):
print("Teacher teaches.")
class TeachingAssistant(Student, Teacher):# Hybrid inheritance
def assist(self):
print("TA assists in teaching and learning.")
ta = TeachingAssistant()
[Link]() # From Person
[Link]() # From Student
[Link]() # From Teacher
[Link]() # Own method
THE END
Prepared By: Dr. Ankita Sharma
Assistant Professor
USICT, GGSIPU

References:
i. Python Official Documentation: [Link] .
ii. "Learning Python" by Mark Lutz
iii. "Python Programming" by Reema Thareja

You might also like