装饰器只被调用一次,在装饰函数第一次定义之后。因此,这两种技术(使用 @wrap 和 bar = wrap(bar))是相同的:
>>> def wrap(f):
... print 'making arr'
... arr = []
... def inner():
... arr.append(2)
... print arr
... f()
... return inner
...
>>> @wrap
... def foo():
... print 'foo was called'
...
making arr
>>> foo()
[2]
foo was called
>>> foo()
[2, 2]
foo was called
>>> def bar():
... print 'bar was called'
...
>>> bar = wrap(bar)
making arr
>>> bar()
[2]
bar was called
在这两种情况下,很明显 arr 仅在调用 wrap(f) 时创建,而 wrap 仅在首次声明 foo 和 bar 时调用。
至于将参数传递给装饰函数的情况,请记住装饰器将函数作为参数并返回该函数的修改版本。因此,装饰器通常采用一个参数,即它正在修改的函数。它返回一个新函数,装饰器可以将它返回的函数定义为接受任意数量的参数(例如,*args)。装饰器甚至可以返回一个为其装饰的方法接受太多参数的函数。
>>> def wrap_with_arg(f):
... def wrap(*args):
... print 'called with %d arguments' % len(args)
... f(args)
... return wrap
...
>>> @wrap_with_arg
... def baz(arg):
... print 'called with argument %r' % arg
...
>>> baz(3)
called with 1 arguments
called with argument 3
>>> baz(3, 4)
called with 2 arguments
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<input>", line 4, in wrap
File "<input>", line 3, in baz
TypeError: not all arguments converted during string formatting
虽然最终 baz 会引发错误,但请注意在引发错误之前如何正确打印参数的数量。