Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #闭包:闭包函数引用外部函数的变量(一般不能是全局变量),且闭包函数必须返回一个函数对象
- #闭包形成一个封闭的对象,这个对象包括引用的所有外部和内部变量以及表达式
- #所以在返回闭包函数前,对象是不变的
- def line_conf(a,b):
- def line(x):
- return a * x + b
- return line
- #定义两条直线
- line_A = line_conf(2,1)
- line_B = line_conf(3,2)
- #打印x对应y的值
- print(line_A(1))
- print(line_B(1))
- #显示查看闭包
- #主函数内的闭包不引用外部变量,就不存在闭包,主函数的_closure__属性永远为None
- #主函数没有return闭包函数,也不存在闭包,此时主函数没有__closure__属性
- # def line_conf2():
- # a = 1
- # b = 2
- #
- # def line2(x):
- # print(x+1)
- # # return line2
- # return a+b
- #
- # L = line_conf2()
- # print(line_conf2().__closure__)
- # for i in line_conf2().__closure__:
- # print(i.cell_contents)
- #闭包经典案例---容易出错
- #最终结果不是0 1 4 9 而是 9 9 9 9
- l = []
- for i in range(4):
- def func():
- return i*i
- l.append(func)
- for s in l:
- print(s())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement