Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

python function overloading

# Python method overloading in a class
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 _(self, *args):
        string = ' '.join(args)
        print(string)
        
    @add.register(list)
    def _(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]

# for independent methods
from datetime import date, time

@singledispatch
def format(arg):
    print(arg)

@format.register            # syntax version 1
def _(arg: date):
    print(f"{arg.day}-{arg.month}-{arg.year}")

@format.register(time)      # syntax version 2
def _(arg):
    print(f"{arg.hour}:{arg.minute}:{arg.second}")

format("today")                      # today
format(date(2021, 5, 26))            # 26-5-2021
format(time(19, 22, 15))             # 19:22:15
 
PREVIOUS NEXT
Tagged: #python #function #overloading
ADD COMMENT
Topic
Name
3+8 =