闭包

闭包

闭包:内部函数对外层作用域而非全局作用域的引用

name = "summer"
def fun1():
    def inner():
        print(name)
    print(inner.__closure__)
    return inner

f = fun1()
f() #None  summer



def func1():
    name = "sss"
    def inner():
        print(name)
    print(inner.__closure__)
    return inner
f1 = func1()
f1()  #(<cell at 0x101d5c048: str object at 0x1007de420>,)
 

上面的name在全局作用域中,下面的name在局部作用域中,判断闭包函数的方法__closure__,有返回值则是闭包函数,返回None则不是。所以下面的函数inner为闭包函数

命名空间

每次执行一个函数时, 就会创建新的局部命名空间。该命名空间代表一个局部环境,其中包含函数参数的名称和在函数体内赋值的变量名称.

作用域

global 和 nonlocal关键字
当内部作用域想修改外部作用域的变量时,就要用到global和nonlocal关键字了。

#!/usr/bin/python3
以下实例修改全局变量 num:
num = 1
def fun1():
    global num  # 需要使用 global 关键字声明
    print(num) 
    num = 123
    print(num)
fun1()
以上实例输出结果:
1
123
如果要修改嵌套作用域(enclosing 作用域,外层非全局作用域)中的变量则需要 nonlocal 关键字了,如下实例:

#!/usr/bin/python3
 
def outer():
    num = 10
    def inner():
        nonlocal num   # nonlocal关键字声明
        num = 100
        print(num)
    inner()
    print(num)
outer()
以上实例输出结果:

100
100
另外有一种特殊情况,假设下面这段代码被运行:

#!/usr/bin/python3
 
a = 10
def test():
    a = a + 1
    print(a)
test()
以上程序执行,报错信息如下:

Traceback (most recent call last):
  File "test.py", line 7, in <module>
    test()
  File "test.py", line 5, in test
    a = a + 1
UnboundLocalError: local variable 'a' referenced before assignment
错误信息为局部作用域引用错误,因为 test 函数中的 a 使用的是局部,未定义,无法修改。



name = "summer"
def f1():
    print(name)

def f2():
    name = "rain"
    f1()

f2()  #summer

posted on 2018-08-22 21:27  summer-rain  阅读(94)  评论(0编辑  收藏  举报