装饰器
装饰器
类似于java的切面, 再不更改原函数代码的前提下,动态做一些动作。
一. 简单的装饰器
def logging(func):
def wrapper(*args, **kwargs):
print("logging is running",file=sys.stderr)
func(*args, **kwargs)
return wrapper
def bar():
print('i am bar')
bar= logging(bar)# 返回wrapper函数
bar() # 调用返回的wrapper,内部会执行bar()
上面其实就是装饰器的本质, 为了隐藏
b= logging(bar)
b()
这种丑陋的写法我们可以写成如下的样子
def logging(func):
def wrapper(*args, **kwargs):
print("logging is running",file=sys.stderr)
func(*args, **kwargs)
return wrapper
@logging
def bar():
print('i am bar')
bar()
二. 带参数的装饰器
- 传统写法
import sys
def use_logging(level):
def decorator(func):
def wrapper(*args):
if level == "warn":
print("logging is running",file=sys.stderr)
else:
print("logging is running",file=sys.stdout)
func(*args)
return wrapper
return decorator
# @use_logging(level="warn")
def foo(name):
print("i am %s" % name)
d = use_logging("warn")
f = d(foo)
f("董梦雨")
- 装饰器高级写法
import sys
def logging(level):
def decorator(func):
def wrapper(*args):
if level == "warn":
print("logging is running",file=sys.stderr)
else:
print("logging is running",file=sys.stdout)
func(*args)
return wrapper
return decorator
@logging(level="warn")
def foo(name):
print("i am %s" % name)
foo("董梦雨")