python 闭包内函数调用外函数, 附带斐波拉契数列的实现
两种方法一种是nonlocal可以自动查找上一层的变量注意区别 global全局变量的区别;另一种利用数组实现
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2018-11-12 10:54:17 # @Author : Zhang Rui (1484659706@qq.com) # @Link : https://www.cnblogs.com/mangmangbiluo/ # @Version : $Id$ import os def fa(): a = 0 b = 1 def f2(): nonlocal a nonlocal b c = a + b a, b = b, c # print(a) return a return f2 def fb(): a = [0, 1] def f2(a=a): a[0], a[1] = a[1], a[0] + a[1] # print(a) return a[0] return f2 def fc(): a, b =0, 1 while 1: a, b = b, a+b yield a if __name__ == "__main__": f1 = fa() for i in range(10): a = f1() print(a, end=" ") print() f2 = fb() for i in range(10): a = f2() print(a, end=" ") print() f3 = fc() for i in range(10): print(next(f3), end=" ") print()
fa利用nonlocal,fb利用数组,fc是生成器的实现,下面是输出
1 1 2 3 5 8 13 21 34 55 1 1 2 3 5 8 13 21 34 55 1 1 2 3 5 8 13 21 34 55 [Finished in 0.1s]