I am solving a couple of problems in python
In one of them, its asks me to write a function such that when
examplefunction([1, 2, 3, 4])(10) returns something lets just say 10.
The trouble is, I've never seen notation using double ()() to call a function so far in python.
I've tried looking at multiple posts on stack overflow such as Python: Apply function to values in nested dictionary
But there is really no question like this.
object()() is just _result = object() and _result() chained. As long as the first call returns a callable object, the second call expression can proceed.
Have your examplefunction() call return another function. Functions are objects too, so you could just return an existing function:
def examplefunction():
return secondfunction
def secondfunction():
return 10
at which point examplefunction()() produces 10.
You can also have your examplefunction() call produce a new function object each time, by defining that function object as part of its body:
def examplefunction():
def nestedfunction():
return 10
return nestedfunction
This gives the same result, but the added advantage that nestedfunction() has (read) access to all local names defined in examplefunction (these are called closures); this allows you to parameterise how nestedfunction() behaves:
def examplefunction(base):
def nestedfunction():
return base * 2
return nestedfunction
examplefunction(5)() # produces 10
I suspect that your assignment is trying to teach you these principles.
Functions don't have multiple parameter brackets. Those are just referring to nested functions, or functions that incorporate other functions.
For example:
def func(a):
def func2(b):
return a + b
return func2
Would be invoked like this:
func(1)(2)
(and would return 3 as an answer)
So it appears there are two parameter brackets, but really they are for two different functions!
Hope it helps!
Source
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