【发布时间】:2018-10-01 21:51:15
【问题描述】:
我刚开始学习装饰器。我觉得我了解如何修改装饰器以使用参数,但是我不明白为什么要实现 Python 中的装饰器,因此需要进行此修改。
[编辑:为清楚起见。] 对于没有参数的装饰器,以下是等价的:
@decorate
def function(arg):
pass
function = decorate(function)
那么,对于一个带参数的装饰器,为什么不让下面的等价呢?
@decorate(123)
def function(arg):
pass
function = decorate(function, 123)
我发现这更一致,更容易阅读,也更容易编码。
以下是 python 装饰器的工作方式以及我期望它们的工作方式。 [编辑:我也添加了预期的输出。]:
OUTPUT:
function HELLA NESTED! Decorated with OMG!
function NOT AS NESTED! Decorated with NOT SO BAD!
def python_decorator(dec_arg):
def actual_decorator(func):
def decorated_func(func_arg):
print(func.__name__, func(func_arg), "Decorated with", dec_arg)
return decorated_func
return actual_decorator
@python_decorator("OMG!")
def function(arg):
return arg
function("HELLA NESTED!")
def my_expected_decorator(func, dec_arg):
# I expected the `func` parameter to be like `self` in classes---it's
# always first and is given special meaning with decorators.
def decorated_func(func_arg):
print(func.__name__, func(func_arg), "Decorated with", dec_arg)
return decorated_func
# @my_expected_decorator("NOT SO BAD!") # This is what I expected.
def function(arg):
return arg
function = my_expected_decorator(function, "NOT SO BAD!")
function("NOT AS NESTED!")
我查看了PEP 318 并没有看到装饰器没有以上述方式实现的原因,但我还是这个想法的新手。我觉得上面的改变会让装饰器更容易和更一致的使用。
【问题讨论】: