Python Method Overloading

Cover Image

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


from functools import singledispatchmethod, singledispatch

class Foo:
    def add(self, *args):
        res = 0
        for x in args:
            res += x

    def _add_str(self, *args):
        string = ' '.join(args)

    def _add_list(self, *args):
        myList = []
        for x in args:
            myList += x

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]