【发布时间】: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