嵌套函数如何在Python中工作? [英] How do nested functions work in Python?
问题描述
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
为什么嵌套函数记住第一个值 2
,即使 maker()
Why does the nested function remember the first value 2
even though maker()
has returned and exited by the time action()
is called?
推荐答案
你可以看到它,因为所有的父函数中的变量都被子函数中的实际值所替代。这样,没有必要跟踪父函数的范围,使子函数正确运行。
You can see it as all the variables originating in the parent function being replaced by their actual value inside the child function. This way, there is no need to keep track of the scope of the parent function to make the child function run correctly.
将其视为动态创建函数。
See it as "dynamically creating a function".
def maker(n):
def action(x):
return x ** n
return action
f = maker(2)
--> def action(x):
--> return x ** 2
这是python中的基本行为, / p>
This is basic behavior in python, it does the same with multiple assignments.
a = 1
b = 2
a, b = b, a
Python将此读为
Python reads this as
a, b = 2, 1
它基本上是在做任何事情之前插入值。
It basically inserts the values before doing anything with them.
这篇关于嵌套函数如何在Python中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!