Nuances when working with an internal function in Python
Not only can Python have nested functions, but one function can also return another. For example, let the function outer return the source code of the function inner as a result:
def outer():
def inner():
return '+++'
return inner
Let's write the call to outer into the variable res:
res = outer()
print(res)
After executing the code, an object with a function will be output:
<function outer.<locals>.inner at 0x000001564A212B90>
If you call the variable res with parentheses, the message '+++' will be returned:
print(res()) # '+++'
The code can be rewritten so that res writes outer with two parentheses - to call itself and the function inner. From this it follows that additional parentheses can be written to the right of the outer function according to the number of functions nested in it:
res = outer()()
print(res) # '+++'
The following code is given:
def outer():
def inner(num):
return num + 2
return inner
res = outer()(3)
print(res)
Tell me what will be output to the console.
The following code is given:
def outer():
def inner(txt):
return 'hello, ' + txt
return inner
res = outer()
print(res)
Tell me what will be output to the console.