How do nested functions work in Python?(嵌套函数如何在 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()
在 action()
时已经返回并退出叫?
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 中的基本行为,对于多个赋值也是如此.
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 中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:嵌套函数如何在 Python 中工作?


基础教程推荐
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 求两个直方图的卷积 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 包装空间模型 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01