Hi I am a new to Python. Can somebody explain me how this program works and particularly the flow of program. Why the output shows as "inner". Regards and Thanks in advance.
def outer():
x = 3
def inner():
y = 4
result = x+y
return result
return inner
a = outer()
print(a.__name__)
Output:
output:
inner
when you call outer()
function on line 9 it returns the inner
function and assign that return value to name a
. So a
is a function (i.e. inner
) object
__name__ is not the interesting part. That is not much different than doing this:
def inner():
return 4
a = inner
print(a.__name__)
Output:
inner
The interesting part of your example is "x". I modify the code a for a more interesting example:
def outer(x):
def inner(y=4):
return y**x
return inner
square = outer(2)
cube = outer(3)
print(square(2), cube(2))
I assign two variables, "square" and "cube". When I call square(2) it returns 2 squared. When I call cube(2) it returns 2 cubed. How is this possible? In both cases I call the same function, inner(2). How can it act differently?
You may think that square is assigned to refer to inner(). If you print the type of square (print(type(square))) it even prints <class 'function'>, but this is only partially true. square is a closure, a combination of a function and a context. When you call square(2), you call inner(2), but you are calling inner(2) in a context where x == 2. When you call cube(2) you call inner(2) in a context where x == 3.