0

I'm learning Python lately (Dec.'20) and found this concept is very convoluted. Let's say I have a function. How can I tell if a particular objects type can be applied to this kind of function overloading?

def compute(a, b, c):
    return (a+b) * c

It works fine with some of these object type - number, string, but not others.

>>> a, b, c=1,2,3
>>> a, b, c = 'hi', 'U', 3   # okay

>>> a, b, c = [1], [2,3], 3  # okay
>>> a, b, c = {1}, {2}, 3    # it's set()
3
  • This is because strings and matrices can have maths done to them. "string" * 3 = "stringstringstring" however where you have used {} curley bracket. These cannot have maths done to them Commented Jan 10, 2021 at 19:00
  • @Evorage that's too broad of a statement. {1} - {2} is legal. The problem is that sets don't support +. Commented Jan 10, 2021 at 19:01
  • This isn't function overloading, python doesn't have function overloading. Python is a dynamically typed language, and this is resolved at runtime when the function is called. To know what inputs a function expects you must read the documentation Commented Jan 10, 2021 at 21:34

2 Answers 2

1

Taking the + as an example, a data type must implement the __add__() (magic/special/"dunder") method to meaningfully use the + operator. In your examples, it is defined for integers, strings and lists, but not for sets.

The Python Data Model is the reference document if you want to learn more about this topic, but as a starting point you may find this article useful.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the pointers! Will read and dive in... Appreciate it. Sorry that I cannot vote yet...
0

If you want to know whether a particular object, say x has an operator overloaded, or what we call magic method in Python, you can check:

hasattr(x, '__add__')  # for + and similarly for any other.

Of course, you can define one such method for a class you want, if it does not exist.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.