I've been having trouble understanding what h(a)(b)
means. I'd never seen one of those before yesterday, and I couldn't declare a function this way:
def f (a)(b): return a(b)
When I tried to do def f (a, b):
, it didn't work either. What do these functions do? How can I declare them? And, finally, what's the difference between f(a, b)
and f(a)(b)
?
Luckily, you can write functions that take in more than one parameter by defining as many parameters as needed, for example: def function_name(data_1, data_2):
Python has no means of overloading a name. You can only have one function for each name. Unlike Ruby, you must use parentheses to call functions. A function name without parentheses simply refers to the function as an object.
Note that when you are working with multiple parameters, the function call must have the same number of arguments as there are parameters, and the arguments must be passed in the same order.
In Python 3.7 and newer, there is no limit.
Functions with multiple parameter brackets don't exist, as you saw when you tried to define one. There are, however, functions which return (other) functions:
def func(a): def func2(b): return a + b return func2
Now when you call func()
it returns the inner func2
function:
>>> func2 = func(1) # You don't have to call it func2 here >>> func2(2) 3
But if you don't need the inner function later on, then there's no need to save it into a variable and you can just call them one after the other:
>>> func(1)(2) # func(1) returns func2 which is then called with (2) 3
This is a very common idiom when defining decorators that take arguments.
Notice that calling func()
always creates a new inner function, even though they're all named func2
inside of the definition of our func
:
>>> f1 = func(1) >>> f2 = func(1) >>> f1(1), f2(1) (2, 2) >>> f1 is f2 False
And, finally, what's the difference between
f(a, b)
andf(a)(b)
?
It should be clear now that you know what f(a)(b)
does, but to summarize:
f(a, b)
calls f
with two parameters a
and b
f(a)(b)
calls f
with one parameter a
, which then returns another function, which is then called with one parameter b
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With