1 理解
装饰器出现的原因: 为了优化程序的代码,增强函数的逻辑性
装饰器可以完成的功能如下:
①函数执行之前,加一些逻辑性的步骤
②函数执行之后,加一些逻辑性的步骤
2 分类
2.1 不传参的装饰器
2.1.1 语法
def 函数名1(func_name):
def 函数名2():
func_name()
return 函数名2
def 函数名3():
2.1.2 示例代码
def decoration(func_time):
def x1():
print("函数执行之前")
func_time()
print("函数执行之后")
return x1
@decoration
def x2():
print("加了装饰器的函数")
x2()
2.1.3 运行截图
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/adf8d97d21ac45c287a0b3ed6e49e097.png#pic_center)
2.2 传参的装饰器
2.2.1 语法
def 函数名1(func_name):
def 函数名2(p,q):
func_name(p,q)
return 函数名3对应的返回值
return 函数名2
def 函数名3(x,y):
2.2.2 示例代码
def decoration(func_time):
def x1(t1, t2):
print("函数执行之前")
print(f"t1的值为:{t1},t2的值为:{t2}")
func_time(t1, t2)
print("函数执行之后")
return "调用装饰器函数的返回值"
return x1
@decoration
def x2(m, n):
print(f"m的值为:{m},n的值为:{n}")
print("加了装饰器的函数")
print(x2(6, 8))
2.2.3 运行截图
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/0a330ff1d5d44270a38f456aa232e0dd.png#pic_center)