python装饰器decorator的应用
python中的装饰器类似于java中的AOP切面编程的思想,下面通过demo教大家如何实现
(1)一个最简单的装饰器 demo1
#一个最简单的装饰器
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
结果:
Something is happening before the function is called.
Hello!
Something is happening after the function is called.
(2)装饰器中如何传递函数中的参数 demo2
#装饰器中如何传递函数中的参数
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Something is happening before the function is called.")
result = func(*args, **kwargs)
print("Something is happening after the function is called.")
return result
return wrapper
@my_decorator
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
结果:
Something is happening before the function is called.
Hello, Alice!
Something is happening after the function is called.
(3)多个装饰器 demo3
#多个装饰器
def decorator1(func):
def wrapper(*args, **kwargs):
print("Decorator 1")
return func(*args, **kwargs)
return wrapper
def decorator2(func):
def wrapper(*args, **kwargs):
print("Decorator 2")
return func(*args, **kwargs)
return wrapper
@decorator1
@decorator2
def say_hi():
print("Hi!")
say_hi()
结果:
Decorator 1
Decorator 2
Hi!
(4)当作注解,使用 @装饰器名(装饰器参数) 绑定到函数上 demo4
#conding=utf-8
#给装饰器 传递参数
def decorator(arg_1, arg_2):
"""
装饰器是一个自定义函数,可以接收我们指定的参数,
其内部内嵌了两层函数,用于接收函数本身和函数参数.
因此我们有两种使用装饰器的方法:(该样例使用第一种)
① 当作注解,使用 @装饰器名(装饰器参数) 绑定到函数上
② 当作函数,使用 装饰器名(装饰器参数)(函数名)(函数参数) 来一次性调用
我们在装饰器内部拿到了函数和其参数,因此有较大的自由度可以决定如何调用目标函数。
"""
def wrapper(func):
def func_wrapper(*args, **kw):
print(func.__name__)
print(f"装饰器参数1: {arg_1}, 装饰器参数2: {arg_2}")
print("执行函数前做点什么")
result = func(*args, **kw)
print("执行函数后做点什么")
print(f"目标函数运行返回值:{result}")
return result
return func_wrapper
return wrapper
# 加法函数
@decorator("参数1", "参数2")
def add(arg_1: int, arg_2: int):
print(f"目标函数开始执行, 函数参数为: {arg_1},{arg_2}")
return arg_1 + arg_2
if __name__ == '__main__':
print("=" * 10)
# 绑定注解形式调用
add(3, 5)
结果:
==========
add
装饰器参数1: 参数1, 装饰器参数2: 参数2
执行函数前做点什么
目标函数开始执行, 函数参数为: 3,5
执行函数后做点什么
目标函数运行返回值:8
(5)当作函数,使用 装饰器名(装饰器参数)(函数名)(函数参数) 来一次性调用 demo5
#conding=utf-8
#给装饰器 传递参数
def decorator(arg_1, arg_2):
"""
创建装饰器。
装饰器是一个自定义函数,可以接收我们指定的参数,
其内部内嵌了两层函数,用于接收函数本身和函数参数.
因此我们有两种使用装饰器的方法:(该样例使用第二种)
① 当作注解,使用 @装饰器名(装饰器参数) 绑定到函数上
② 当作函数,使用 装饰器名(装饰器参数)(函数名)(函数参数) 来一次性调用
我们在装饰器内部拿到了函数和其参数,因此有较大的自由度可以决定如何调用目标函数。
"""
def wrapper(func):
def func_wrapper(*args, **kw):
print(func.__name__)
print(f"装饰器参数1: {arg_1}, 装饰器参数2: {arg_2}")
print("执行函数前做点什么")
result = func(*args, **kw)
print("执行函数后做点什么")
print(f"目标函数运行返回值:{result}")
return result
return func_wrapper
return wrapper
# 加法函数
@decorator("参数1", "参数2")
def add(arg_1: int, arg_2: int):
print(f"目标函数开始执行, 函数参数为: {arg_1},{arg_2}")
return arg_1 + arg_2
if __name__ == '__main__':
print("=" * 10)
# 绑定注解形式调用
# 一次性调用
decorator("参数_1", "参数_2")(add)(3,5)
结果:
==========
func_wrapper
装饰器参数1: 参数_1, 装饰器参数2: 参数_2
执行函数前做点什么
add
装饰器参数1: 参数1, 装饰器参数2: 参数2
执行函数前做点什么
目标函数开始执行, 函数参数为: 3,5
执行函数后做点什么
目标函数运行返回值:8
执行函数后做点什么
目标函数运行返回值:8
(6)类装饰器 demo6
#conding=utf-8
#类装饰器
class MyDecorator:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print("Something is happening before the function is called.")
result = self.func(*args, **kwargs)
print("Something is happening after the function is called.")
return result
@MyDecorator
def say_goodbye():
print("Goodbye!")
say_goodbye()
结果:
Something is happening before the function is called.
Goodbye!
Something is happening after the function is called.
源码获取方式(免费):
(1)登录-注册:http://resources.kittytiger.cn/
(2)搜索:python装饰器decorator的应用
浙公网安备 33010602011771号