(PWP) Presentation
(PWP) Presentation
Both overloading and overriding are concepts related to polymorphism, which allows objects of
different classes to respond to the same method call in different ways. However, they differ in their
implementation and purpose.
1. Overloading
● Definition: Overloading refers to the ability to define multiple methods or operators with the
same name but different signatures (number or types of arguments) within the same class.
● Python's Approach: Python doesn't support traditional method overloading in the way
languages like Java or C++ do. In those languages, you can define multiple methods with the
same name but different parameter lists.
○ Default arguments: You can define a single method with optional arguments, allowing
it to be called with varying numbers of arguments.
○ Variable-length arguments (*args and **kwargs): These allow a function to accept any
number of positional or keyword arguments.
○ Operator overloading: Python allows you to redefine the behavior of built-in operators
(like +, -, *, etc.) for custom classes.
calc = Calculator()
print(calc.add(5)) # Output: 5
print(calc.add(5, 10)) # Output: 15
print(calc.add(5, 10, 15)) # Output: 30
● Operator Overloading:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"({self.x}, {self.y})"
p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2
print(p3) # Output: (4, 6)
2. Overriding
● Definition: Overriding occurs when a subclass provides a specific implementation for a
method that is already defined in its superclass.
● Purpose: It allows a subclass to customize or extend the behavior inherited from its parent
class.
● How it Works: When a method is called on an object of the subclass, Python first looks for the
method in the subclass. If found, it executes the subclass's implementation. Otherwise, it
searches in the superclass.
Example of Overriding:
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")
animal = Animal()
dog = Dog()
cat = Cat()
● Overloading:
○ Multiple methods with the same name in the same class.
○ Different signatures (number/types of arguments).
○ Simulated in Python using default arguments, *args, **kwargs, and operator
overloading.
● Overriding:
○ A subclass provides a different implementation for a method already defined in its
superclass.
○ Same method signature.
○ Used to customize or extend inherited behavior.