鱼C论坛

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

[技术交流] python学习笔记之内嵌函数和闭包

[复制链接]
发表于 2017-7-17 10:19:19 | 显示全部楼层 |阅读模式

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

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

x
内嵌函数和闭包
  • 内嵌函数:在函数内部创建另一个函数
    1.   >>> def fun1():
    2.          print('fun1() is running...')
    3.          def fun2():
    4.             print('fun2() is running...')
    5.          fun2()

    6.   >>> fun1()
    7.   fun1() is running...
    8.   fun2() is running...
    复制代码

内部函数的整个作用域都在外部函数之内
  • 闭包:在一个内部函数里,对外部作用域(但不是在全局作用域)的变量进行引用,内部函数就会被认为是闭包
    1.   >>> def funx(x):
    2.          def funy(y):
    3.                 return x*y
    4.          return funy

    5.   >>> i = funx(8)
    6.   >>> type(i)
    7.   <class 'function'>
    8.   >>> i(5)
    9.   40
    10.   >>> funx(8)(5)
    11.   40
    复制代码
    在内部函数funy()中,对外部作用域(但不是全局作用域)的变量x进行引用,则funy()构成闭包
  • 列表不存放在栈里面,可以再外部函数和内部(嵌)函数之间进行数据交换、赋值、修改
    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#26>", line 1, in <module>
    10.       fun1()
    11.   File "<pyshell#25>", line 6, in fun1
    12.       return fun2()
    13.   File "<pyshell#25>", line 4, in fun2
    14.       x *= x
    15.   UnboundLocalError: local variable 'x' referenced before assignment
    16.   >>> def fun1():
    17.          x = [5]
    18.          def fun2():
    19.             x[0] *= x[0]
    20.             return x[0]
    21.      return fun2()

    22.   >>> fun1()
    23.   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鱼币 +3 收起 理由
小甲鱼 + 3

查看全部评分

本帖被以下淘专辑推荐:

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

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-4-28 07:00

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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