python def 之外的装饰器

python decorator above something other than def

python 中装饰器的常用结构是

@decorator
def function(x):
    <code here>

相当于

def function(x):
    <code here>
function = decorator(function)

(至少,这是我的理解。)现在假设我们有一个函数mystery_func,我们没有自己定义,但我们仍然想用decorator装饰。我们可以吗

@decorator
mystery_func

或者我们必须做

mystery_func = decorator(mystery_func)

获得与

相同的效果
@decorator
def mystery_func(args):
    <code here>

答案是否定的,@语法不能用于任意行,需要使用mystery_func = decorator(mystery_func)。像这样使用 @ 语法是 SyntaxError.

您也可以使用 class decorators 即 "something other than def":

例如

@foo
@bar
class A:
  pass

但是你在这里提到的:

@decorator
mystery_func

是一个SyntaxError