
python 闭包输出谜题
在 python 中,闭包是指可以访问其嵌套函数中局部变量的函数。然而,有时闭包的行为可能令人费解,导致无法输出预期结果。
问题
以下代码片段中,为何第一种写法无法输出任何内容,而第二种可以输出呢?
立即学习“Python免费学习笔记(深入)”;
# 第一写法
def startgame(fps):
def update():
print('FPS: ', fps)
return update # 返回函数
# 调用#1
update = startgame(60)
# 第二写法
def startgame(fps):
def update():
print('FPS: ', fps)
return update() # 返回调用后的函数
# 调用#2
update = startgame(60)
update()
答案
这并不是闭包问题,而是函数调用的误解。
第一种写法
在第一种写法中,startgame 返回一个函数 update,但是并没有调用它。因此,也没有输出。
第二种写法
在第二种写法中,startgame 返回的是调用后的函数 update,它立即被调用了。因此,会输出 fps: 60。
结论
因此,当需要调用函数时,确保不返回函数本身,而是返回其调用后的结果,这样才能获得预期输出。
以上就是Python闭包迷思:为什么一种写法无法输出,另一种却能打印FPS?的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号