装饰器(函数)

1 函数作用域:L E G B

x=10
def f():
    t=5
    def inner():
        count=7
        print (a)
        return 1

2 高阶函数

1 函数名可以作为参数输入

2 函数名还可以作为返回值

3 闭包:如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内置函数就被认为是闭包(closure)。

#!/usr/bin/env python3.8
# __author: "smoke"
# date: 2021/1/10 下午8:20

def outer():
    x = 10
    def inner():    #条件一:inner内部函数
        print(x)    #条件二:外部环境的一个变量
    return inner    #结论:内部函数inner就是一个闭包

outer()()

/home/smoke/PycharmProjects/pythonProject/venv/bin/python /home/smoke/PycharmProjects/pythonProject/lean_python/closure.py
10

Process finished with exit code 0

#!/usr/bin/env python3.8
# __author: "smoke"
# date: 2021/1/10 下午8:20

def outer():
    x = 10
    def inner():
        print(x)
    return inner

f = outer()
f()

/home/smoke/PycharmProjects/pythonProject/venv/bin/python /home/smoke/PycharmProjects/pythonProject/lean_python/closure.py
10

Process finished with exit code 0

#!/usr/bin/env python3.8
# __author: "smoke"
# date: 2021/1/10 下午8:20

def outer():
    x = 10
    def inner():
        print(x)
    return inner

inner()    #局部变量,全局无法调用

/home/smoke/PycharmProjects/pythonProject/venv/bin/python /home/smoke/PycharmProjects/pythonProject/lean_python/closure.py
Traceback (most recent call last):
  File "/home/smoke/PycharmProjects/pythonProject/lean_python/closure.py", line 11, in <module>
    inner()
NameError: name 'inner' is not defined

Process finished with exit code 1

关于闭包:闭包=内部函数+定义函数时的环境

#!/usr/bin/env python3.8
# __author: "smoke"
# date: 2021/1/10 下午8:20

def outer():
    x = 10
    def inner():
        c = 100
        print(c)
    return inner

f = outer()
f()

/home/smoke/PycharmProjects/pythonProject/venv/bin/python /home/smoke/PycharmProjects/pythonProject/lean_python/closure.py
100

Process finished with exit code 0

#!/usr/bin/env python3.8
# __author: "smoke"
# date: 2021/1/10 下午8:20

def outer(x):
    def inner():
        print(x)
    return inner

f = outer(8)
f()

/home/smoke/PycharmProjects/pythonProject/venv/bin/python /home/smoke/PycharmProjects/pythonProject/lean_python/closure.py
8

Process finished with exit code 0