【问题标题】:python decorator above something other than defpython 装饰器高于 def 以外的东西
【发布时间】:2016-05-27 15:21:53
【问题描述】:

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>

【问题讨论】:

  • 这不需要提问,您可以在交互式解释器中测试此问题,所用时间比撰写问题所需的时间要短。
  • 如果您没有安装 Python,Ideone 适合非交互式测试,PythonAnywhere's "Try IPython" online thing 为您提供在线 IPython 环境,这通常比常规交互式测试更好Python 解释器。
  • @ShadowRanger 这仍然是一个有效的问题,也许OP 不知道class 装饰器不是def

标签: python decorator python-decorators


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您也可以使用class decorators,它是“def 以外的东西”:

    例如。

    @foo
    @bar
    class A:
      pass
    

    但是你在这里提到的:

    @decorator
    mystery_func
    

    SyntaxError

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-28
      • 1970-01-01
      • 2015-11-04
      • 2012-01-06
      • 2014-01-01
      • 2010-10-09
      • 2014-02-14
      相关资源
      最近更新 更多