i have a question with this lines of code :
def first():
print('Hello From First')
def wrapper():
print('Hi From Second')
return wrapper
first()
# a = first()
# a()
Outpute:
Hello From First
when i call first() the inside Function not print but if i uncomment that 2 lines the output change to this :
Hello From First
Hello From First
Hi From Second
i wonder why assign function to variable and call that variable change the outpue?
thanks
CodePudding user response:
In the first case, you just execute first()
what causes the first print. It also return the function wrapper since this is the return value, but nothing's done with this value.
When you uncomment the last 2 lines:
- in
a = first()
you executefirst()
again what causes the addition print ofHello From First
, but this timea
also contains a pointer to the wrapper function. - You execute
a()
what causes execution of wrapper function that printsHi From Second
. Hope it was clear.
CodePudding user response:
Because inside first()
function you return a pointer to the wrapper()
function, so when you do: a=first()
the first()
function is executed and "Hello From First" is printed.
Than the function returns the pointer to the function wrapper()
and a contains it.
So when you do a()
it actually executes wrapper()