Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. #闭包:闭包函数引用外部函数的变量(一般不能是全局变量),且闭包函数必须返回一个函数对象
  2. #闭包形成一个封闭的对象,这个对象包括引用的所有外部和内部变量以及表达式
  3. #所以在返回闭包函数前,对象是不变的
  4. def line_conf(a,b):
  5. def line(x):
  6. return a * x + b
  7. return line
  8.  
  9. #定义两条直线
  10. line_A = line_conf(2,1)
  11. line_B = line_conf(3,2)
  12.  
  13. #打印x对应y的值
  14. print(line_A(1))
  15. print(line_B(1))
  16.  
  17. #显示查看闭包
  18. #主函数内的闭包不引用外部变量,就不存在闭包,主函数的_closure__属性永远为None
  19. #主函数没有return闭包函数,也不存在闭包,此时主函数没有__closure__属性
  20. # def line_conf2():
  21. # a = 1
  22. # b = 2
  23. #
  24. # def line2(x):
  25. # print(x+1)
  26. # # return line2
  27. # return a+b
  28. #
  29. # L = line_conf2()
  30. # print(line_conf2().__closure__)
  31. # for i in line_conf2().__closure__:
  32. # print(i.cell_contents)
  33.  
  34. #闭包经典案例---容易出错
  35. #最终结果不是0 1 4 9 而是 9 9 9 9
  36.  
  37. l = []
  38.  
  39. for i in range(4):
  40. def func():
  41. return i*i
  42. l.append(func)
  43. for s in l:
  44. print(s())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement