-5

When I come across closure in python, from the below code, I don't understand how the values for the arguments assigned for x and y when calling the function. In Point 1, we passing argument value 5 for x. It is then assigned to x in the function. In Point 2, we passing 7 to inc5, My doubt arises here, again the value 7 should assign to x, but instead how come it is assigning to y.

def makeInc(x):
    def inc(y):
        return y + x
    return inc

inc5 = makeInc(5) #Point 1
inc5(7) #Point 2
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
Green
  • 577
  • 3
  • 10
  • 28

2 Answers2

2

I can't understand why you think 7 should be assigned to x. The outer function makeInc returns the inner function inc, and it's that which you assign to inc5. So inc5 accepts the argument y, and that's what is bound to the value 7.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
1

At Point 1 you are passing a varialbe inc5 the returning result of a makeInc function, which will be another function inc with a local variable x set to 5. Then you call for this new function and pass a 7 as its one and only parameter y.

konart
  • 1,714
  • 1
  • 12
  • 19