Answer the question
In order to leave comments, you need to log in
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
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
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question