Python Method Overloading
What is Method Overloading?
It’s a concept in the OOP That that allows you to create multiple methods with the same name within a class, These methods can have different parameters types or number of arguments, and Python will choose the appropriate method to call based on the arguments you provide.
Why ?!! It make your code cleaner when call the overloaded method in different places
How
from functools import singledispatchmethod, singledispatch
class Foo:
@singledispatchmethod
def add(self, *args):
res = 0
for x in args:
res += x
print(res)
@add.register(str)
def _add_str(self, *args):
string = ' '.join(args)
print(string)
@add.register(list)
def _add_list(self, *args):
myList = []
for x in args:
myList += x
print(myList)
obj = Foo()
obj.add(1, 2, 3) # 6
obj.add('I', 'love', 'Python') # I love Python
obj.add([1, 2], [3, 4], [5, 6]) # [1, 2, 3, 4, 5, 6]