鱼C论坛

 找回密码
 立即注册
查看: 3686|回复: 0

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

[复制链接]
发表于 2017-6-25 23:41:41 | 显示全部楼层 |阅读模式

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

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

x
1.修改函数体内的全局变量的值的方法——global关键字
当在函数体内对全局变量修改时,程序会自动生成一个和全局变量名一样的局部变量,但是由于作用域的不同,仍是无法改变全局变量的值,从而保护全局变量;如果实在想改变全局变量就要用到global关键字;
  1. >>> count = 5
  2. >>> def MyFun():
  3.         count = 10
  4.         print(10)

  5.        
  6. >>> MyFun()
  7. 10
  8. >>> print(count)
  9. 5
  10. >>> def MyFun():
  11.         global count
  12.         count = 10
  13.         print(10)

  14. >>> MyFun()
  15. 10
  16. >>> print(count)
  17. 10
复制代码

2.内嵌函数(又称内部函数)——简单的说就是函数中的函数
允许在函数内部创建另一个函数这种函数就是内嵌函数
  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#23>", line 1, in <module>
  13.     fun2()
  14. NameError: name 'fun2' is not defined
复制代码

3.闭包closure
函数是编程重要的语法结构,一种编程的放失;不同的编程语言实现闭包的方式不同;
Python中闭包从表现形式上定义为:如果在一个内部函数里对外部作用域(但不是在全局作用域)的变量进行引用,内部函数就被认为是闭包;
  1. >>> def FunX(x):
  2.         def FunY(y):  #这里的FunY()就是一个闭包
  3.                 return x * y
  4.         return FunY   #直接返回闭包函数名

  5. >>> i = FunX(8)    #返回过来的是一个函数对象赋值给 i
  6. >>> i
  7. <function FunX.<locals>.FunY at 0x025B6A98>
  8. >>> type(i)
  9. <class 'function'>
  10. >>> i(5)           # i 可以直接进行函数调用
  11. 40
  12. >>> FunX(8)(5)     #此种形式同样可进行调用
  13. 40
  14. >>> FunY(5)        #闭包无法直接调用
  15. Traceback (most recent call last):
  16.   File "<pyshell#36>", line 1, in <module>
  17.     FunY(5)
  18. NameError: name 'FunY' is not defined
复制代码

4.在内嵌函数内修改外部函数内定义的变量值的方法——nonlocal
  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#44>", line 1, in <module>
  10.     Fun1()
  11.   File "<pyshell#43>", line 6, in Fun1
  12.     return Fun2()
  13.   File "<pyshell#43>", line 4, in Fun2
  14.     x *= x
  15. UnboundLocalError: local variable 'x' referenced before assignment
复制代码

改造代码
  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
复制代码

使用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
复制代码

评分

参与人数 1鱼币 +4 收起 理由
小甲鱼 + 4 支持楼主!

查看全部评分

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-4-28 08:16

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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