0

Using multiple dispatch to allow for function overloading within OOP, is it possible for me to run the following code:

@dispatch(int)
  def __init__(self, radius: int):

However, remove the int, as the attribute being passed in could either be an int or a str.

MrDDog
  • 7
  • 6
  • What's the point of overloading if you accept any type? – matszwecja Jan 17 '23 at 12:18
  • @matszwecja I am completing a programming trail and I am NOT allowed to change the initial code, there are instances where 1 is passed in and instances where "one" is passed in, I can obviously do: if x == "one": x = 1 But as I am not allowed to change the original code I HAVE to do it within my class, I could duplicate the above text for str but then I would have to do it for a lot of different combinations. – MrDDog Jan 17 '23 at 12:44

1 Answers1

0

Use the functools.singledispatchmethod to overload a class method by its arguments' annotation.

from functools import singledispatchmethod


class Generic:
    """
    >>> _ = Generic(1)
    __init__ got int
    >>> _ = Generic(1.0)
    __init__ got float
    >>> _ = Generic(None)
    default __init__
    """

    @singledispatchmethod
    def __init__(self, radius):
        print("default __init__")

    @__init__.register
    def _(self, radius: int):
        print("__init__ got int")

    @__init__.register
    def _(self, radius: float):
        print("__init__ got float")
Artyom Vancyan
  • 5,029
  • 3
  • 12
  • 34