|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
闭包结构中含有多层函数嵌套,其中内层函数是不是只能通过return结束?
好奇内层函数除了return语句结束外,还有没有可能通过其他方式结束,如print,或者内层函数通过()执行等?请各位大神指定!!!
本帖最后由 jackz007 于 2024-8-31 01:02 编辑
1、外层函数必须使用 return 返回内层函数的名称,这是因为如果不这样,在闭包函数的外部就无法访问到其内层函数。
2、内层函数是否使用 return 结束完全取决于需要,如果这个函数需要反馈给调用者一个结果,那就使用 return 返回,否则,就不需要。
【有 return 实例】:
- def fib() :
- a , b = 0 , 0
- def inner() :
- nonlocal a , b
- a , b = b , a + b
- if not b : b += 1
- return a # 每次调用闭包函数需要取得斐波那契数列新的数据,所以,内层函数需要返回计算结果。
- return inner # 外层函数必须返回内层函数的名称
- fx = fib()
- x = []
- for _ in range(20):
- x . append(fx()) # 每次调用闭包函数需要取得斐波那契数列新的数据,所以,内层函数需要返回计算结果。
- print(x)
复制代码
运行实况:
- D:\[exercise]\Python>python x.py
- [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]
- D:\[exercise]\Python>
复制代码
【无 reuturn 实例】:
- def foo() :
- c = 0
- def inner() :
- nonlocal c
- c += 1
- print("%2d. 欢迎来到 FishC" % c)
- return inner # 外层函数必须返回内层函数的名称
- ex = foo()
- for _ in range(20):
- ex()
复制代码
运行实况:
- D:\[exercise]\Python>python x.py
- 1. 欢迎来到 FishC
- 2. 欢迎来到 FishC
- 3. 欢迎来到 FishC
- 4. 欢迎来到 FishC
- 5. 欢迎来到 FishC
- 6. 欢迎来到 FishC
- 7. 欢迎来到 FishC
- 8. 欢迎来到 FishC
- 9. 欢迎来到 FishC
- 10. 欢迎来到 FishC
- 11. 欢迎来到 FishC
- 12. 欢迎来到 FishC
- 13. 欢迎来到 FishC
- 14. 欢迎来到 FishC
- 15. 欢迎来到 FishC
- 16. 欢迎来到 FishC
- 17. 欢迎来到 FishC
- 18. 欢迎来到 FishC
- 19. 欢迎来到 FishC
- 20. 欢迎来到 FishC
- D:\[exercise]\Python>
复制代码
|
|