2

In C/C++, when we define a function signature, We emphasize on return type(as well) in addition to arguments that a function is allowed to take.

In python, a function can or cannot(None) return value, But the function signature only constitutes arguments that a function is allowed to take.

How do we understand this in python?

overexchange
  • 15,768
  • 30
  • 152
  • 347

1 Answers1

3

Python does not use static typing.

In C++, the type signature is actually considered part of the name of the function; if you call foo(2) and foo("wow"), you are actually calling two different functions.

In Python, any particular function is just a function object. If you have a reference to it, you can call it; and you can use its name to look it up, to get a reference to it. Either way, the "type signature" doesn't matter.

Also, in C++, if you want to overload a function, you will declare it multiple times, with different type signatures; in Python, you will declare it one time, but take advantage of "duck typing" to make it do the right thing with different arguments. Here is an example:

// C++
int add2(int a, int b)
{
    return a + b;
}

int add2(char const *a, int b)
{
    return atoi(a) + b;
}

int add2(int a, char const *b)
{
    return a + atoi(b);
}

int add2(char const *a, char const *b)
{
    return atoi(a) + atoi(b);
}

# Python
def add2(a, b):
    return int(a) + int(b)

With the above declarations, in both Python and C you would be able to call the add2() function with any combination of integer values and/or strings. (I didn't put in any error handling on the strings, but the C++ code will do the right thing as long as you pass in sensible strings like "3".) The difference is that in C++ you need to use types to declare multiple versions of the function, and convert arguments as necessary; while in Python, you can pass in anything as a or b, and the calls to int() will attempt to coerce the passed-in values to int type.

That single Python function will add any two values that can be converted to int type. It will handle strings like "3", float values like 3.1415, Boolean values (True converts to 1, False converts to 0), etc. When you pass in int values, the call to int() just returns the value back unchanged; otherwise int() forces a conversion to int type and raises an exception if the conversion fails.

This is an example of how Python is more convenient, and you can get a lot of work done in a few lines of Python. (Of course Python is much slower than C++, so Python is not suitable for some applications.)

steveha
  • 74,789
  • 21
  • 92
  • 117