我发现我可以用两种不同的方式装饰一个函数,以在函数上实现相同的“装饰”:
def greeting(expr):
def greeting_decorator(func):
def function_wrapper(x):
print(expr + ", " + func.__name__ + " returns:")
func(x)
return function_wrapper
return greeting_decorator
def foo(x):
return x
greeting2 = greeting("Good morning!")
foo = greeting2(foo)
...或
def greeting_decorator2(func, expr):
def function_wrapper(x):
print(expr + ", " + func.__name__ + " returns:")
print(func(x))
return function_wrapper
def foo(x):
return x
foo = greeting_decorator2(foo, "Good morning!")
请注意,可以更改第一个示例以使用“at”注释:
@greeting("Good morning!")
def foo(x):
return x
但是使用带有第二个装饰器函数示例的注释会导致崩溃,这是可以理解的。
我的问题是,除了要包装的函数之外,哪些方法包含装饰器函数的附加参数是首选?第二个似乎更容易包围,如果需要更多的额外参数,可能更具可扩展性。使用它有什么缺点吗?