How do nested functions work in Python?

后端 未结 9 483
春和景丽
春和景丽 2020-12-01 04:50
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)) # stil         


        
9条回答
  •  时光取名叫无心
    2020-12-01 05:41

    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
    

提交回复
热议问题