-3

hi I want to know how to create 3 functions with the same name for my HW. the Explanation video used functions with numbers adding and multiply them the HW is about (creating 3 functions with the same name and then calling them). I just need a clue how it works and I will do the rest by my self.

  • [How Do I Ask a Homework Question](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions) – baduker Apr 15 '21 at 09:35
  • 1
    Python does not allow overloading functions (though now possible through with singledisplatch), check here https://stackoverflow.com/questions/7113032/overloaded-functions-in-python. – Louis Lac Apr 15 '21 at 09:39

1 Answers1

0

You can have a function that takes in a variable number of arguments.

So what are multimethods? I'll give you my own definition, as I've come to understand them: a function that has multiple versions, distinguished by the type of the arguments. (Some people go beyond this and also allow versions distinguished by the value of the arguments; I'm not addressing this here.)

As a very simple example, let's suppose we have a function that we want to define for two ints, two floats, or two strings. Of course, we could define it as follows:

    def foo(a, b):
    if isinstance(a, int) and isinstance(b, int):
        ...code for two ints...
    elif isinstance(a, float) and isinstance(b, float):
        ...code for two floats...
    elif isinstance(a, str) and isinstance(b, str):
        ...code for two strings...
    else:
        raise TypeError("unsupported argument types (%s, %s)" % (type(a), type(b)))

But this pattern gets tedious. (It also isn't very OO, but then, neither are multimethods, despite the name, IMO.) So what could this look like using multimethod dispatch? Decorators are a good match:

    from mm import multimethod

    @multimethod(int, int)
    def foo(a, b):
        ...code for two ints...

    @multimethod(float, float):
    def foo(a, b):
        ...code for two floats...

    @multimethod(str, str):
    def foo(a, b):
        ...code for two strings...

Sayan
  • 93
  • 3
  • 9