简体   繁体   中英

Functions can return another function use in Python

It's not hard to understand "functions are objects we can return a function from another function". But how is below code working?

# Functions can return another function 

def create_adder(x): 
    def adder(y): 
        return x+y 

    return adder 

add_15 = create_adder(15) 

print (add_15(10)) 

The result is 25.

Personal understanding:

create_adder(x) function will return the reference of adder function, kind like:

<function create_adder.<locals>.adder at 0x7fd83e19fe18>

15 is x in it(create_adder) and add_15 is object of create_adder function, so add_15(10) might have taken x as the argument.Then how did it get the value of y?No variable created for it and no argument passed for it?

Can someone help me point out the misunderstanding?

A couple more comments should make it clear:

# Functions can return another function 

def create_adder(x): 
    def adder(y): 
        return x+y 

    return adder 


add_15 = create_adder(15) 

# def create_adder(15): 
#     def adder(y): 
#         return 15+y 

#     return adder 


print (add_15(10)) 

# add_15(10) = adder(10)
# adder(10) # returns 15 + 10 = 25

add_15 = create_adder(15)
-----> here, x will be assigned as 15 and create_adder(15) will have the address of adder function

print (add_15(10)) -----> that address will be passed here to assign 10 to y, where already x is having value of 15, and x+y ie 25 will be returned

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