闭包和装饰器的相关知识点
闭包
- 闭包是指当调用一个函数的时候,返回另一个函数,比如调用A函数,返回B函数,那么B函数就是一个闭包
- 闭包的结构及案例:
# 将中国的钱换算成外国的钱
# 外国钱 = 外国的汇率 × 中国的钱
# 定义一个函数rate,当调用函数时,返回函数money的引用
def rate(rate):
def money(money):
print(rate * money)
return money
# 假设美金的汇率为0.7
usa_rate = rate(0.7) # 这里的usa_rate 就是一个闭包的引用
usa_money = usa_rate(100)
usa_money = usa_rate(200)
# 假设日币的汇率为100
jp_rate = rate(100) # 这里的jp_rate 是一个闭包的引用
jp_money = jp_rate(100)
jp_money = jp_rate(1)
装饰器
- 闭包主要的应用就是充当装饰器
- 装饰器完成的功能是,在不改变函数的代码的前提下,给函数增加一些新的功能
- 形式为@<函数名>(实际上==》<函数名> = set_fun(<函数名>))
# 给一个函数添加验证操作
# 闭包
def set_fun(test):
def call_fun():
print("添加权限")
test()
return call_fun
# 装饰器
@set_fun # ==> test = set_fun(test)
def test():
print("this is a test")
test()
装饰器执行步骤解析
通用装饰器模板
def set_fun(func):
def call_fun(*args, **kwargs):
return func(*args, **kwargs)
return call_fun
用一个装饰器装饰多个函数
# 通用装饰器可以装饰任意函数
def set_fun(func):
def call_fun(*args, **kwargs):
print("权限验证")
return func(*args, **kwargs)
return call_fun
@set_fun
def test1():
print("this is test 1")
@set_fun
def test2(data):
print(data)
print("this is test2")
@set_fun
def test3(data):
return data
test1()
print("*"*50)
test2(123)
print("*"*50)
print(test3(456))
结果
权限验证
this is test 1
**************************************************
权限验证
123
this is test2
**************************************************
权限验证
456
一个函数被多个装饰器装饰
# 创建多个装饰器
def set_fun1(test):
print("this is set_fun1")
def call_fun(*args, **kwargs):
print("this is call_fun1")
return test(*args, **kwargs)
return call_fun
def set_fun2(test):
print("this is set_fun2")
def call_fun(*args, **kwargs):
print("this is call_fun2")
return test(*args, **kwargs)
return call_fun
def set_fun3(test):
print("this is set_fun3")
def call_fun(*args, **kwargs):
print("this is call_fun3")
return test(*args, **kwargs)
return call_fun
@set_fun1
@set_fun2
@set_fun3
# 注意执行顺序,秋裤大法,先外后内,先近后远
def test(data):
print("this is func_test")
test(123)
结果
this is set_fun3
this is set_fun2
this is set_fun1
this is call_fun1
this is call_fun2
this is call_fun3
this is func_test
装饰器使用场景
1. 引入日志
2. 函数执行时间统计
3. 执行函数前预备处理
4. 执行函数后清理功能
5. 权限校验等场景
6. 缓存
7. dengdeng