python装饰器(decorator)
装饰器(decorator)
def trace(fn):
def wrapped(x):
print('-> ', fn.__name__, '(', x, ')')
return fn(x)
return wrapped
@trace
def triple(x):
return 3 * x
s = triple(12)
print(s)
'''
-> triple ( 12 )
36
'''
在这个例子中,定义了一个高阶函数 trace,它返回一个函数,该函数在调用其参数前先输出一个打印语句来显示该参数。triple 的 def 语句有一个注解(annotation) @trace,它会影响 def 执行的规则。和往常一样,函数 triple 被创建了。但是,名称 triple 不会绑定到这个函数上。相反,这个名称会被绑定到在新定义的 triple 函数调用 trace 后返回的函数值上。代码中,这个装饰器等价于:
def triple(x):
return 3 * x
triple = trace(triple)
再比如:
def func(f):
def h(x):
return f(f(x))
return h
@func
def f(x):
return x * 2
print(f(3)) # 3*2*2 = 12
装饰器符号 @ 也可以后跟一个调用表达式。跟在 @ 后面的表达式会先被解析(就像上面的 'trace' 名称一样),然后是 def 语句,最后将装饰器表达式的运算结果应用到新定义的函数上,并将其结果绑定到 def 语句中的名称上。 比如:
def decorator_factory(condition):
def decorator(func):
def wrapper(*args, **kwargs):
if condition:
print("Before function execution")
result = func(*args, **kwargs)
if condition:
print("After function execution")
return result
return wrapper
return decorator
condition = True # 可根据需要设置装饰器的条件
@decorator_factory(condition)
def greet(name):
print("Hello, " + name)
greet("Alice")
condition = True时会打印
Before function execution
Hello, Alice
After function execution
condition = False时只会打印
Hello, Alice

浙公网安备 33010602011771号