-1

So I need to create overload function sum() for adding two numbers, one should take integer values and another float. The input will be only 2 integer numbers for both sum() functions.

How can I distinguish between the first sum() function and second sum() function then? The first sum() function is supposed to be for integer parameters and the second is supposed to be for floating-point. But if the last function is always the one getting called for regardless of whether the parameter is integer or floating-point. I tired different casting but no success

I have for example these function, but can not understand how to overload them

def add(a, b):
    return a + b

def add(a:float, b:float):
    return  a + b

I can not use dispatch() , isintance() or any other modules

D.L
  • 4,339
  • 5
  • 22
  • 45
Mikimitor
  • 1
  • 2
  • When you searched "Function Overloading in python" in a search engine, did anything useful come up? – dfundako Feb 02 '23 at 16:51
  • not really, only found python overloading when same functions have different number of parameters, but in my case I have only 2 but different types. And they are using thing dispatch() , isintance() I am not allowed to use – Mikimitor Feb 02 '23 at 16:52
  • Why can't you use core features of Python? After all that's why they're there - to be used – DarkKnight Feb 02 '23 at 16:55
  • 2
    What about sums of a combination of ints and floats? Python is dynamic and `a + b` will work on any mutually addable things. Define `sum` once and it will work for ints and floats. In fact, the builtin `sum` already works... and why have a function for `+` anyway? – tdelaney Feb 02 '23 at 16:55
  • 1
    Look at `typing.overload`. You never really have multiple functions; just one function with different type annotations for use by tools like `mypy`. – chepner Feb 02 '23 at 16:56
  • When you say you need two different functions, do you really mean that, or can just one function that deals with both instances? If you just need the function to definitely return an integer in either case, just do `return int(a + b)` – Matt Pitkin Feb 02 '23 at 16:57
  • Overloading in a static language can be used to do the same thing to different types of objects. Python doesn't need to do that. If you need a function to do different things depending on the type of object, then use the `isinstance` function. For instance, if your function takes either a file object or a string path name to a file, you use `isinstance`. So I guess the question is, why do you want to overload? The answer would differ. – tdelaney Feb 02 '23 at 16:59
  • @MattPitkin Yes it can be solved with one function and if statements, but I need two add() functions – Mikimitor Feb 02 '23 at 17:04
  • @tdelaney is it just the way the problem is rated, 2 same add() functions but different output. isinstance() is not allowed to use – Mikimitor Feb 02 '23 at 17:05
  • 1
    @Mikimitor - it sounds like the problem is not solvable. You can't have multiple like-named functions in the same module. In C++ for example, overloaded functions are actually "munged" into unique names by the compiler. Since python functions don't know type, there is no way for them to do that. If you need different functions for different types and you can't do `isinstance`, then you'll have to name them differently yourself. `add_int` and `add_float` perhaps. – tdelaney Feb 02 '23 at 17:16
  • "one should take integer values and another float. The input will be only 2 integer numbers for both sum() functions." -- could you clarify this? If the second function takes float values, how is it that its input would only be integers? – slothrop Feb 02 '23 at 17:34
  • I guess `functools.singledispatch` is not allowed? – slothrop Feb 02 '23 at 17:44
  • @slothrop not , Actually I need to have like this, so input is two integers, but the output is different maybe something to do with type /* >>> def sum(a, b): #for integer return a + b >>> def sum(a, b): #for float return a + b... >>> sum(1, 3) 4 >>> sum(1, 3) 4.0 */ – Mikimitor Feb 02 '23 at 17:52
  • Ah - so is it the case that "one should *return* integer values and another float"? Rather than "take"? – slothrop Feb 02 '23 at 17:53
  • @slothrop yes they should return – Mikimitor Feb 02 '23 at 17:57
  • So: the same expression `sum(1,3)` should sometimes return `4` and sometimes return `4.0`? What rule should determine when it returns which one? – slothrop Feb 02 '23 at 17:58
  • @slothrop they both should output the results – Mikimitor Feb 02 '23 at 18:07
  • sorry, I still don't get it! So if I execute: `x = sum(1, 3)` - what is then the value of `x`? – slothrop Feb 02 '23 at 18:08

3 Answers3

0

Based on your comments, I'm guessing you looked at this geeksforgeeks article. If you look closely, it did not overload the function with a different number of arguments because the last defined function will always be the defined function.

At the end of the day, Python does not do function overloading like in C++ or Java. There is always only one definition for a function. You'll have to parse the inputs in order to decide the behavior within the function itself. I'm a little confused why you can't use isinstance but I suppose you can get around it with type.

Michael Cao
  • 2,278
  • 1
  • 1
  • 13
  • solved it with isinstance(), but needs to be done whitout it. I guess for type, I need if else staments, which is not allowed – Mikimitor Feb 02 '23 at 17:09
  • You can use `type(a)`. – Michael Cao Feb 02 '23 at 17:10
  • what if I put change the order of execution: Like first I ask for input for two integers, then i call add() function and result will be sum of two integers. After that I define a function add() but it will convert the integer input to the float and then return me a sum, is it considered as overload ? – Mikimitor Feb 02 '23 at 18:06
  • No, that's still just overwriting what the function does, not overload it, which once again, Python does not support. – Michael Cao Feb 02 '23 at 18:29
  • Thank you for your reply, Could you tell, here in this example, is it consiirerd as overloading in python ? `number = 2 def addition(num): total = num + number print("The sum of function with one parameter is: ", total) addition(9) def addition(num, num1): total = num + num1 print("The sum of function with two parameters is:", total) addition(10, 11)` – Mikimitor Feb 02 '23 at 18:35
  • 1
    No, any time you call `addition` after running the previous code will always run the `addition` with two arguments. Once again, Python does not support overloading. – Michael Cao Feb 02 '23 at 18:38
0

If you have a statically typed language, a add function would need variants for each type of thing you want added. The underlying machine code for adding integers is different than floats, and each would need to be in its own function.

Python isn't that way. In python, + is translated to a call to the object's __add__ method and the object itself decides what it means to add. Take your single sum function and you could add integers, floats, and even concatenate strings.

>>> def sum(a, b):
...     return a + b
... 
>>> sum(1, 3)
4
>>> sum(1.1, 3.3)
4.4
>>> sum("foo", "bar")
'foobar'

How about adding million element arrays? It'll do that, too.

>>> import numpy as np
>>> a1 = np.ones((1000,1000), dtype=int)
>>> a2 = np.zeros((1000,1000), dtype=int)
>>> sum(a1, a2)
array([[1, 1, 1, ..., 1, 1, 1],
       [1, 1, 1, ..., 1, 1, 1],
       [1, 1, 1, ..., 1, 1, 1],
       ...,
       [1, 1, 1, ..., 1, 1, 1],
       [1, 1, 1, ..., 1, 1, 1],
       [1, 1, 1, ..., 1, 1, 1]])
tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • Actually I need to have like this, so inout is two integers, but the output is different maybe something to do with type /* >>> def sum(a, b): #for integer return ... return a + b >>> def sum(a, b): #for float return ... return a + b... >>> sum(1, 3) 4 >>> sum(1, 3) 4.0 */ – Mikimitor Feb 02 '23 at 17:16
  • `for float` isn't a thing. You could do `if type(a) is float:`. That is very close to `if isinstance(a, float):`. – tdelaney Feb 02 '23 at 17:35
  • basically like this but witout using classes and OOP : tdelaney https://stackoverflow.com/a/67830038/21129453 – Mikimitor Feb 02 '23 at 17:58
  • what if I put change the order of execution: Like first I ask for input for two integers, then i call add() function and result will be sum of two integers. After that I define a function add() but it will convert the integer input to the float and then return me a sum, is it considered as overload ? – Mikimitor Feb 02 '23 at 18:05
  • @Mikimitor - I don't that that would be an overload. You could have 2 .py files, say, `int_functions.py` and `float_functions.py` so that you would call them as `int_functions.add(1,2)` and `float_functions.add(1.0, 2.0)`. But thats also not overloading. Overloading is figured out by the compiler, and since python isn't a typed language, it can't do it. The best you'll get is having the function check object types. But if you can't do that (e.g., `isinstance`) then the problem isn't solvable. – tdelaney Feb 02 '23 at 20:00
-1

Python does not support overloading. The best that you can do is remove any type identifiers from the arguments and use if-else statements to change the function of the method depending on the input types.

For example:

def add(a,b):
    if type(a) == float and type(b) == float:
        pass # add floats
    elif type(a) == int and type(b) == int:
        pass # add ints
    else:
        assert False, 'input error, arguments (a,b) need to both be either a float or an int'

or

class integers():
    def __init__(self) -> None:
        pass    
    @classmethod
    def add(cls,a,b):
        return int(a) + int(b)

class floats():
    def __init__(self) -> None:
        pass
    
    @classmethod
    def add(cls,a,b):
        return float(a) + float(b)


a_float_sum = floats.add(1.0, 2.0)
print(f'{a_float_sum=}')

an_int_sum = integers.add(1, 2)
print(f'{an_int_sum=}')

g.newt
  • 105
  • 3
  • yes this is the way I wanted to solve initially , but it is not allowed , I need two functions add() with overloading , not if-else statements – Mikimitor Feb 02 '23 at 17:07
  • what if I put change the order of execution: Like first I ask for input for two integers, then i call add() function and result will be sum of two integers. After that I define a function add() but it will convert the integer input to the float and then return me a sum, is it considered as overload ? – Mikimitor Feb 02 '23 at 18:05
  • Thank you for your reply, Could you tell, here in this example, is it consiirerd as overloading in python ? ```python def function(foo): print(foo) number = 2 def addition(num): total = num + number print("The sum of function with one parameter is: ", total) addition(9) def addition(num, num1): total = num + num1 print("The sum of function with two parameters is:", total) addition(10, 11). ``` – Mikimitor Feb 02 '23 at 18:47
  • No, there is no overloading in Python. Languages like Java and C have overloading functionality. Python, on the other hand, explicitly does not support method overloading. I just edited my answer to include the closest I know of how to method overload. P.S. If you have to use "method overloading" for a python assignment in school or something, it is simply impossible as Python does not support method overloading at all in the same sense as Java and C. There is no way to overload a method in Python, the logic behind method overloading is not coded into the Python compiler like Java or C. – g.newt Feb 03 '23 at 21:39