Home > Blockchain >  assign function to variable in python
assign function to variable in python

Time:04-24

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:

  1. in a = first() you execute first() again what causes the addition print of Hello From First, but this time a also contains a pointer to the wrapper function.
  2. You execute a() what causes execution of wrapper function that prints Hi 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()

Read more here

  • Related