简体   繁体   中英

assign function to variable in python

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM