How do nested functions work in Python?

2019-01-13 17:34发布

def maker(n):
    def action(x):
        return x ** n
    return action

f = maker(2)
print(f)
print(f(3))
print(f(4))

g = maker(3)
print(g(3))

print(f(3)) # still remembers 2

Why does the nested function remember the first value 2 even though maker() has returned and exited by the time action() is called?

9条回答
Root(大扎)
2楼-- · 2019-01-13 18:05

You are basically creating a closure.

In computer science, a closure is a first-class function with free variables that are bound in the lexical environment. Such a function is said to be "closed over" its free variables.

Related reading: Closures: why are they so useful?

A closure is simply a more convenient way to give a function access to local state.

From http://docs.python.org/reference/compound_stmts.html:

Programmer’s note: Functions are first-class objects. A 'def' form executed inside a function definition defines a local function that can be returned or passed around. Free variables used in the nested function can access the local variables of the function containing the def. See section Naming and binding for details.

查看更多
冷血范
3楼-- · 2019-01-13 18:06

People answered correctly about the closure, that is: the valid value for "n" inside action is the last value it had whenever "maker" was called.

One ease way to overcome this is to make your freevar (n) a variable inside the "action" function, which receives a copy of "n" in the moment it is run:

The easiest way to do this is to set "n" as a parameter whose default value is "n" at the moment of creation. This value for "n" stays fixed because default parameters for a function are stored in a tuple which is an attribute of the function itself (action.func_defaults in this case):

def maker(n):
    def action(x, k=n):
        return x ** k
    return action

Usage:

f = maker(2) # f is action(x, k=2)
f(3)   # returns 3^2 = 9
f(3,3) # returns 3^3 = 27
查看更多
别忘想泡老子
4楼-- · 2019-01-13 18:07

You are defining TWO functions. When you call

f = maker(2)

you're defining a function that returns twice the number, so

f(2) --> 4
f(3) --> 6

Then, you define ANOTHER DIFFERENT FUNCTION

g = maker(3)

that return three times the number

g(3) ---> 9

But they are TWO different functions, it's not the same function referenced, each one it's a independent one. Even in the scope inside the function 'maker' are called the same, is't not the same function, each time you call maker() you're defining a different function. It's like a local variable, each time you call the function takes the same name, but can contain different values. In this case, the variable 'action' contains a function (which can be different)

查看更多
登录 后发表回答