鱼C论坛

 找回密码
 立即注册
查看: 2611|回复: 2

[学习笔记] python复盘:020函数:内嵌函数和闭包

[复制链接]
发表于 2020-2-16 10:08:51 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
020函数:内嵌函数和闭包

一、Global关键字
1、屏蔽Shadowing:试图在函数内部修改全局变量时,python会生成一个同名的局部变量,只修改了python创建的局部变量。
  1. >>> count = 5
  2. >>> def Myfun():
  3.         count = 10
  4.         print(10)

  5.        
  6. >>> Myfun()
  7. 10
  8. >>> print(count)
  9. 5
复制代码


2、运用global修改全局变量
  1. >>> def Myfun():
  2.         global count
  3.         count = 10
  4.         print(10)

  5.        
  6. >>> Myfun()
  7. 10
  8. >>> print(count)
  9. 10
复制代码


二、内嵌函数(内部函数)
  1. >>> def fun1():
  2.         print('fun1()正在被调用...')
  3.         def fun2():
  4.                 print('fun2()正在被调用...')
  5.         fun2()

  6.        
  7. >>> fun1()
  8. fun1()正在被调用...
  9. fun2()正在被调用...
  10. >>> fun2()
  11. Traceback (most recent call last):
  12.   File "<pyshell#33>", line 1, in <module>
  13.     fun2()
  14. NameError: name 'fun2' is not defined
复制代码


三、闭包closure
1、闭包:函数式编程的一个重要结构
  1. >>> def funx(x):
  2.         def funy(y):
  3.                 return x * y
  4.         return funy

  5. >>> i = funx(8)
  6. >>> i(5)
  7. 40
  8. >>> funx(8)(5)
  9. 40
复制代码

如果在一个内部函数里【funy】,为在外部作用域【funx】的变量【x】,这个内部函数【funy】就是一个闭包。
2、注意
(1)闭包是由内部函数演变而来,不能在外部函数的外边对内部函数进行调用
(2)闭包中外部函数的局部变量对内部函数的局部变量的关系==全局变量对局部变量的关系:即小对大只能访问不能修改
  1. >>> def fun1():
  2.         x = 5
  3.         def fun2():
  4.                 x *= x
  5.                 return x
  6.         return fun2()

  7. >>> fun1()
  8. Traceback (most recent call last):
  9.   File "<pyshell#58>", line 1, in <module>
  10.     fun1()
  11.   File "<pyshell#57>", line 6, in fun1
  12.     return fun2()
  13.   File "<pyshell#57>", line 4, in fun2
  14.     x *= x
  15. UnboundLocalError: local variable 'x' referenced before assignment
复制代码

3、内部修改外部函数的局部变量
(1)python2:修改容器类型(列表、元组)
  1. >>> def fun1():
  2.         x = [5]
  3.         def fun2():
  4.                 x[0] *= x[0]
  5.                 return x[0]
  6.         return fun2()

  7. >>> fun1()
  8. 25
复制代码

(2)python3:运用nonlocal关键字
  1. >>> def fun1():
  2.         x = 5
  3.         def fun2():
  4.                 nonlocal x
  5.                 x *= x
  6.                 return x
  7.         return fun2()

  8. >>> fun1()
  9. 25
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-2-16 10:36:03 | 显示全部楼层
向你学习!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-2-16 13:24:14 | 显示全部楼层

共勉~
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-3 18:46

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表