M
M
mkone1122021-12-30 14:07:57
Python
mkone112, 2021-12-30 14:07:57

How to implement method overloading in python?

How to implement this behavior in python 3.6?

from datetime import date

class Datepicker:
    def __init__(self, date: date) -> None:
        print('date object')
    def __init__(self, year, month, day) -> None:
        print('args')


Datepicker(date.today())  # date object
Datepicker(2020, 1, 1)  # args
help(Datepicker.__init__)
Help on wrapper_descriptor:

__init__(self, date: date) -> None
__init__(self, year, month, day) -> None

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
mkone112, 2021-12-31
@mkone112

from functools import singledispatch


class Test:
    def __init__(self):
        self.render = singledispatch(self.render)
        self.render.register(str, self._render_str)
        self.render.register(int, self._render_int)

    def render(self, s):
        raise TypeError(f"{type(s)} type isn't supported:")

    def _render_str(self, s, b=None):
        print("render str")

    def _render_int(self, s):
        print("render int")

t = Test()
>> t.render('s')
render str
>> t.render(1)
render int

ps of course this can be implemented using a metaclass - but as for me it's overkill
https://github.com/dabeaz/python-cookbook/blob/mas...

S
shurshur, 2021-12-30
@shurshur

There is no method overloading in python, instead you can accept arbitrary parameters through *args and **kwargs, for example:

def __init__(self, *args):
    if isinstance(args[0], date):
        # это date
    elif all(isinstance(arg, int) for arg in args[0:3]):
        # это 3 int

S
Sergey Karbivnichy, 2021-12-30
@hottabxp

@functools.singledispatch

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question