0

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?

4
  • There is an argument passed form it, in the def of adder, it says y. Commented Apr 13, 2020 at 1:53
  • 3
    Might help if you step through the code in python tutor Commented Apr 13, 2020 at 1:59
  • @Phillyclause89 Thanks, that's super cool. This site would be very helpful for noobs like me. Commented Apr 13, 2020 at 2:10
  • @Chamberlain , Yeah python tutor will work for most short code snippets up to 1000 steps. If your code gets more complex than that or requires libraries not included in Anaconda distribution than I recommend getting a good IDE like PyCharm and learning how to step through code in Debug mode. Commented Apr 13, 2020 at 2:21

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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 i.e 25 will be returned

2 Comments

Please correct your formatting for readability.
This was already suggested here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.