Python | Method Overloading
Last Updated :
12 Sep, 2024
Method Overloading:
Two or more methods have the same name but different numbers of parameters or different types of parameters, or both. These methods are called overloaded methods and this is called method overloading.
Like other languages (for example, method overloading in C++) do, python does not support method overloading by default. But there are different ways to achieve method overloading in Python.
The problem with method overloading in Python is that we may overload the methods but can only use the latest defined method.
Python
# First product method.
# Takes two argument and print their
# product
def product(a, b):
p = a * b
print(p)
# Second product method
# Takes three argument and print their
# product
def product(a, b, c):
p = a * b*c
print(p)
# Uncommenting the below line shows an error
# product(4, 5)
# This line will call the second product method
product(4, 5, 5)
In the above code, we have defined two product methods we can only use the second product method, as python does not support method overloading. We may define many methods of the same name and different arguments, but we can only use the latest defined method. Calling the other method will produce an error. Like here calling product(4,5) will produce an error as the latest defined product method takes three arguments.
Thus, to overcome the above problem we can use different ways to achieve the method overloading.
Method 1 (Not The Most Efficient Method):
We can use the arguments to make the same function work differently i.e. as per the arguments.
Python
# Function to take multiple arguments
def add(datatype, *args):
# if datatype is int
# initialize answer as 0
if datatype == 'int':
answer = 0
# if datatype is str
# initialize answer as ''
if datatype == 'str':
answer = ''
# Traverse through the arguments
for x in args:
# This will do addition if the
# arguments are int. Or concatenation
# if the arguments are str
answer = answer + x
print(answer)
# Integer
add('int', 5, 6)
# String
add('str', 'Hi ', 'Geeks')
Method 2 (Not the efficient one):
We can achieve method overloading in python by user defined function using "None" keyword as default parameter.
Code explanation:
The first parameter of "add" method is set to None. This will give us the option to call it with or without a parameter.
When we pass arguments to the add method (Working):
- The method checks if both the parameters are available or not.
- As we have already given default parameter values as "None", if any of the value is not passed it will remain "None".
- Using If-Else statements, we can achieve method overloading by checking each parameter as single statement.
Python
# code
def add(a=None, b=None):
# Checks if both parameters are available
# if statement will be executed if only one parameter is available
if a != None and b == None:
print(a)
# else will be executed if both are available and returns addition of two
else:
print(a+b)
# two arguments are passed, returns addition of two
add(2, 3)
# only one argument is passed, returns a
add(2)
The problem with above methods is that, it makes code more complex with multiple if/else statement and is not the desired way to achieve the method overloading.
Method 3 (Efficient One):
By Using Multiple Dispatch Decorator
Multiple Dispatch Decorator Can be installed by:
pip3 install multipledispatch
If pip is not installed on your device:
Click here for "Windows"
Click here for "Linux"
Python
from multipledispatch import dispatch
# passing one parameter
@dispatch(int, int)
def product(first, second):
result = first*second
print(result)
# passing two parameters
@dispatch(int, int, int)
def product(first, second, third):
result = first * second * third
print(result)
# you can also pass data type of any value as per requirement
@dispatch(float, float, float)
def product(first, second, third):
result = first * second * third
print(result)
# calling product method with 2 arguments
product(2, 3) # this will give output of 6
# calling product method with 3 arguments but all int
product(2, 3, 2) # this will give output of 12
# calling product method with 3 arguments but all float
product(2.2, 3.4, 2.3) # this will give output of 17.985999999999997
Output:
6
12
17.985999999999997
In Backend, Dispatcher creates an object which stores different implementation and on runtime, it selects the appropriate method as the type and number of parameters passed.
Example of Overriding:
class Parent:
def show(self):
print("Inside Parent")
class Child(Parent):
def show(self):
print("Inside Child")
c = Child()
c.show() # Output: Inside Child
- Overriding refers to the ability of a subclass to provide a specific implementation of a method that is already defined in its superclass. This is a common feature in object-oriented programming and is fully supported in Python. This allows a method to behave differently depending on the subclass that implements it.
- Overloading in Python is not supported in the traditional sense where multiple methods can have the same name but different parameters. However, Python supports operator overloading and allows methods to handle arguments of different types, effectively overloading by type checking inside methods.
Does Python Allow Operator Overloading?
Yes, Python allows operator overloading. You can define your own behavior for built-in operators when they are applied to objects of classes you define. This is done by redefining special methods in your class, such as __add__ for +, __mul__ for *, etc.
Example of Operator Overloading:
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return f"({self.x}, {self.y})"
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return Point(x, y)
p1 = Point(1, 2)
p2 = Point(2, 3)
print(p1 + p2) # Output: (3, 5)
What is __init__ in Python?
The __init__ method in Python is a special method used for initializing newly created objects. It's called automatically when a new object of a class is created. This method can have arguments through which you can pass values for initializing object attributes.
Example of __init__:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
p = Person("John", 30)
p.greet() # Output: Hello, my name is John and I am 30 years old.
What is Encapsulation in Python?
Encapsulation is a fundamental concept in object-oriented programming that involves bundling the data (attributes) and methods (functions) that operate on the data into a single unit or class. It restricts direct access to some of the object's components, which can prevent the accidental modification of data and allows for safer and more structured code. In Python, encapsulation is implemented using private (denoted by double underscores __) and protected (denoted by single underscore _) attributes and methods.
Example of Encapsulation:
class Account:
def __init__(self, owner, amount=0):
self.owner = owner
self.__balance = amount # Private attribute
def deposit(self, amount):
if amount > 0:
self.__balance += amount
print("Deposit successful")
else:
print("Deposit amount must be positive")
def get_balance(self):
return self.__balance
acct = Account("John")
acct.deposit(100)
print(acct.get_balance()) # Output: 100
# print(acct.__balance) # This will raise an error because __balance is private
Similar Reads
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Classes and Objects A class in Python is a user-defined template for creating objects. It bundles data and functions together, making it easier to manage and use them. When we create a new class, we define a new type of object. We can then create multiple instances of this object type.Classes are created using class ke
6 min read
Python objects A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to
2 min read
Class and Object
self in Python classIn Python, self is a fundamental concept when working with object-oriented programming (OOP). It represents the instance of the class being used. Whenever we create an object from a class, self refers to the current object instance. It is essential for accessing attributes and methods within the cla
6 min read
Class and Instance Attributes in PythonClass attributes: Class attributes belong to the class itself they will be shared by all the instances. Such attributes are defined in the class body parts usually at the top, for legibility. Python # Write Python code here class sampleclass: count = 0 # class attribute def increase(self): samplecla
2 min read
Create a Python SubclassIn Python, a subclass is a class that inherits attributes and methods from another class, known as the superclass or parent class. When you create a subclass, it can reuse and extend the functionality of the superclass. This allows you to create specialized versions of existing classes without havin
3 min read
Inner Class in PythonPython is an Object-Oriented Programming Language, everything in Python is related to objects, methods, and properties. A class is a user-defined blueprint or a prototype, which we can use to create the objects of a class. The class is defined by using the class keyword.Example of classPython# creat
5 min read
Python MetaClassesThe key concept of python is objects. Almost everything in python is an object, which includes functions and as well as classes. As a result, functions and classes can be passed as arguments, can exist as an instance, and so on. Above all, the concept of objects let the classes in generating other c
9 min read
Creating Instance Objects in PythonIn Python, an instance object is an individual object created from a class, which serves as a blueprint defining the attributes (data) and methods (functions) for the object. When we create an object from a class, it is referred to as an instance. Each instance has its own unique data but shares the
3 min read
Dynamic Attributes in PythonDynamic attributes in Python are terminologies for attributes that are defined at runtime, after creating the objects or instances. In Python we call all functions, methods also as an object. So you can define a dynamic instance attribute for nearly anything in Python. Consider the below example for
2 min read
Constructors in PythonIn Python, a constructor is a special method that is called automatically when an object is created from a class. Its main role is to initialize the object by setting up its attributes or state. The method __new__ is the constructor that creates a new instance of the class while __init__ is the init
3 min read
Why Python Uses 'Self' as Default ArgumentIn Python, when defining methods within a class, the first parameter is always self. The parameter self is a convention not a keyword and it plays a key role in Pythonâs object-oriented structure.Example:Pythonclass Car: def __init__(self, brand, model): self.brand = brand # Set instance attribute s
3 min read
Encapsulation and Access Modifiers
Encapsulation in PythonIn Python, encapsulation refers to the bundling of data (attributes) and methods (functions) that operate on the data into a single unit, typically a class. It also restricts direct access to some components, which helps protect the integrity of the data and ensures proper usage.Table of ContentEnca
6 min read
Access Modifiers in Python : Public, Private and ProtectedPrerequisites: Underscore (_) in Python, Private Variables in PythonEncapsulation is one of the four principles used in Object Oriented Paradigm. It is used to bind and hide data to the class. Data hiding is also referred as Scoping and the accessibility of a method or a field of a class can be chan
9 min read
Access Modifiers in Python : Public, Private and ProtectedPrerequisites: Underscore (_) in Python, Private Variables in PythonEncapsulation is one of the four principles used in Object Oriented Paradigm. It is used to bind and hide data to the class. Data hiding is also referred as Scoping and the accessibility of a method or a field of a class can be chan
9 min read
Private Variables in PythonPrerequisite: Underscore in PythonIn Python, there is no existence of âPrivateâ instance variables that cannot be accessed except inside an object. However, a convention is being followed by most Python code and coders i.e., a name prefixed with an underscore, For e.g. _geek should be treated as a n
3 min read
Private Methods in PythonEncapsulation is one of the fundamental concepts in object-oriented programming (OOP) in Python. It describes the idea of wrapping data and the methods that work on data within one unit. This puts restrictions on accessing variables and methods directly and can prevent the accidental modification of
6 min read
Protected variable in PythonPrerequisites: Underscore ( _ ) in Python A Variable is an identifier that we assign to a memory location which is used to hold values in a computer program. Variables are named locations of storage in the program. Based on access specification, variables can be public, protected and private in a cl
2 min read
Inheritance
Inheritance in PythonInheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (called a child or derived class) to inherit attributes and methods from another class (called a parent or base class). This promotes code reuse, modularity, and a hierarchical class structure. In this arti
7 min read
Method Overriding in PythonMethod overriding is an ability of any object-oriented programming language that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, the same parameter
7 min read
Operator Overloading in PythonOperator Overloading means giving extended meaning beyond their predefined operational meaning. For example operator + is used to add two integers as well as join two strings and merge two lists. It is achievable because '+' operator is overloaded by int class and str class. You might have noticed t
8 min read
Python super()In Python, the super() function is used to refer to the parent class or superclass. It allows you to call methods defined in the superclass from the subclass, enabling you to extend and customize the functionality inherited from the parent class.Syntax of super() in PythonSyntax: super()Return : Ret
8 min read
Multiple Inheritance in PythonInheritance is the mechanism to achieve the re-usability of code as one class(child class) can derive the properties of another class(parent class). It also provides transitivity ie. if class C inherits from P then all the sub-classes of C would also inherit from P. Multiple Inheritance When a class
5 min read
What Is Hybrid Inheritance In Python?Inheritance is a fundamental concept in object-oriented programming (OOP) where a class can inherit attributes and methods from another class. Hybrid inheritance is a combination of more than one type of inheritance. In this article, we will learn about hybrid inheritance in Python. Hybrid Inheritan
3 min read
Multilevel Inheritance in PythonPython is one of the most popular and widely used Programming Languages. Python is an Object Oriented Programming language which means it has features like Inheritance, Encapsulation, Polymorphism, and Abstraction. In this article, we are going to learn about Multilevel Inheritance in Python. Pre-Re
3 min read
Multilevel Inheritance in PythonPython is one of the most popular and widely used Programming Languages. Python is an Object Oriented Programming language which means it has features like Inheritance, Encapsulation, Polymorphism, and Abstraction. In this article, we are going to learn about Multilevel Inheritance in Python. Pre-Re
3 min read
Polymorphism
Abstraction
Special Methods and Testing
Additional Resources