Python 装饰器
装饰器简述
装饰器(decorator),又称“装饰函数”,即一种返回值也是函数的函数,可以称之为“函数的函数”。其目的是在不对现有函数进行修改的情况下,实现额外的功能。最基本的理念来自于一种被称为“装饰模式”的设计模式。在 Python 中,装饰器属于纯粹的“语法糖”,不使用也没关系,但是使用的话能够大大简化代码,使代码更加易读。装饰器可以基于函数实现也可以基于类实现,两种实现的装饰器使用方法基本固定,使用装饰器步骤如下:
- 定义装饰函数(类)
- 定义业务函数
- 业务函数调用装饰函数
装饰器案例
案例1、不改动业务函数基础上增加新功能
def decorator_demo1(func): '''装饰器函数''' def inner(): func() print('这是添加的新功能!!!') return inner # @decorator_demo1 等同与 f1 = decorator_demo1(f1) @decorator_demo1 def f1(): '''业务函数''' print('''This is f1()''') @decorator_demo1 def f2(): '''业务函数''' print('''This is f2()''')
效果
This is f1() 这是添加的新功能!!! This is f2() 这是添加的新功能!!!
Python 支持多个装饰器同时使用
def decorator_demo01(func): '''装饰器1''' def inner(): print('this is decorator_demo01') return f"<b> {func()} </b>" return inner def decorator_demo02(func): '''装饰器2''' def inner(): print('this is decorator_demo02') return f"<b> {func()} </b>" return inner @decorator_demo01 @decorator_demo02 def f1(): '''业务函数''' print("this is f1") return "hello world" res = f1() print(res)
运行效果
this is decorator_demo01 this is decorator_demo02 this is f1 <b> <b> hello world </b> </b>
案例2、带参装饰器
def decorator_demo01(f1): '''装饰器''' print("-正在装饰-") def inner(a, b): print("正在验证") f1(a, b) return inner @decorator_demo01 def f1(a, b): '''业务函数''' print(a + b) f1(0, 5 )
输出
-正在装饰-
正在验证
5
案例3、通用装饰器
def decorator_demo01(func): '''装饰器''' def inner(*args, **kvargs): print('logging') res = func(*args, **kvargs) # 保留返回数据 return res # 返回调用信息 return inner @decorator_demo01 def test1(): '''无参函数''' print("this is test1 No args") @decorator_demo01 def test2(): '''无参函数''' print("this is test2 No args") return "This's test2 return info" @decorator_demo01 def test3(info): '''无参函数''' print(f"this is test3 tith args {info}") res1 = test1() print(res1) res2 = test2() print(res2) res3 = test3("hello test3") print(res3)
输出
logging this is test1 No args None logging this is test2 No args This's test2 return info logging this is test3 tith args hello test3 None

浙公网安备 33010602011771号