0

I was learning the concept of decorators in python from the following link :

http://www.python-course.eu/python3_decorators.php

I have a basic doubt for the following code snippet in it :

def f(x):

    def g(y):
        return y + x + 3 
    return g

nf1 = f(1)

nf2 = f(3)

print(nf1(1))

print(nf2(1))

In this page , it is written that the outputs of the last two lines are going to be '5' and '7' respectively . But as I can see we are only passing the value for 'x' , where does it get the value for 'y' from ? How does it assign value to 'Y' to calculate the output ?

RvdK
  • 19,580
  • 4
  • 64
  • 107
itp dusra
  • 153
  • 1
  • 5
  • These are closures, not decorators. A decorator takes a *function* as an argument, and returns a new function based on the input. A closure is (roughly) a function that "remembers" the value of a local variable in the scope where it is defined. The two concepts are related in that a decorator often returns a closure that calls the original function. – chepner Oct 22 '16 at 11:45
  • That is to say, `g` is a closure, and `f` is just a function that returns a closure. – chepner Oct 22 '16 at 11:51

1 Answers1

1

Function f creates and returns a new function named g.

So, this code creates two g functions by passing x=1 and x=3:

nf1 = f(1)

nf2 = f(3)

Then the g functions (stored in nf1 and nf2) are called with argument y=1:

print(nf1(1))

print(nf2(1))

Maybe (or maybe not) it would have been more understandable if they wrote the equivalent:

print(f(1)(1))  # x=1, y=1
print(f(3)(1))  # x=3, y=1
zvone
  • 18,045
  • 3
  • 49
  • 77
  • Could you clarify a bit more as to why y = 1 ? – itp dusra Oct 22 '16 at 09:59
  • @itpdusra `nf1` **is** `g`, because `f` returns `g`. Function `g` takes one argument: `y`, so `nf1` takes one argument: `y`, because `nf1` is `g`. I would expect that part to be easier to understand ;) The really tricky question is how `nf1` and `nf2` have different value of `x`, when they are both just `g`. For that, it may be good to read [this answer about closures](http://stackoverflow.com/a/4020443/389289) (although, that is a bit more advanced topic). – zvone Oct 22 '16 at 15:05