-1

I'm struggling to understand Function closures properly. For example in the code below I am unclear as to how the function knows that in the statement times3(2) that x=2? Also, after reading documentations I still can't fully understand the purpose of closures.

def make_multiplier_of(n):
    def multiplier(x):
        return x * n
    return multiplier

times3 = make_multiplier_of(3)
times3(2) #How does the function know that x=2 here?

Thanks a lot

user131983
  • 3,787
  • 4
  • 27
  • 42
  • 2
    `times3` is *actually `multiplier`*, the argument `2` is passed to the parameter `x` of that function. It is `n` that's affected by the closure, not `x`. – jonrsharpe Dec 11 '14 at 13:04
  • 2
    I don't get what you don't get... You are calling the function so obviously it knows about its own arguments. It knows about `n` because that's what a closure do, but `x` is just a plain argument. – Bakuriu Dec 11 '14 at 13:05
  • see http://stackoverflow.com/questions/4020419/closures-in-python. it will help. – Vishnu Upadhyay Dec 11 '14 at 13:08

1 Answers1

2

When you are calling make_multiplier_of(3), the function is returning multiplier such that

def multiplier(x):
    return x*3

So times3 = make_multipiler(3) is assigning this particular multiplier function to times3. The same way that when you are doing myLength=len, myLength is the len function and you can call myLength("foo")

times3 is thus this multiplier function. So when you times3(2), you are doing (this particular) multiplier(2)

fredtantini
  • 15,966
  • 8
  • 49
  • 55