【发布时间】:2014-09-24 06:55:12
【问题描述】:
我无法理解装饰器在 Python (2.7.2) 中的工作原理。我有以下代码:
def verbose(function):
print 'i am verbose and func is ' + function.__name__
def wrapper2(func):
print 'func is ' + repr(func)
result = function(func)
return result
return wrapper2
@verbose
def more(function):
print 'i am more and func is ' + function.__name__
def wrapper1(*args, **kwargs):
print 'args' + repr(args)
result = function(*args)
return result
return wrapper1
@more
def hello(*args):
print(sum(args))
当我跑步时:
>>> hello(1,2,3)
这是我得到的:
i am verbose and func is more
func is <function hello at 0x1015338c0>
i am more and func is hello
args(1, 2, 3)
6
我无法想象生成此输出的调用顺序。我认为下面的调用仍然会产生相同的输出,我很想了解装饰装饰器在这个特定示例中是如何工作的。
>>> verbose(more)(hello)(1,2,3)
i am verbose and func is more
func is <function hello at 0x101533d70>
i am more and func is hello
args(1, 2, 3)
6
【问题讨论】:
-
您的代码会生成 NameError,因为您尝试在定义之前使用装饰器。你真的在
more上面定义了verbose吗?此外,即使您这样做,您显示的某些输出也会在定义hello时生成,而在定义more时会生成一些输出,而不是在调用hello时生成。您的示例中的python>>提示符是什么? -
修复了名称错误。是的,当我定义
more和定义hello方法时会生成一些输出。我只是在这里粘贴以确保两种调用方式生成相同的输出。