请看以下实例:
>>> def spamrun(fn):
... def sayspam(*args):
... print "spam, spam, spam"
... return sayspam
...
>>> @spamrun
... def useful(a, b):
... print a**2 + b**2
...
>>> useful(3,4)
spam, spam, spam
请参考python主页中的文档:http://www.python.org/dev/peps/pep-0318/,相信会对修饰符有一个更深入的认识。
更多例子:
Listing 1. Bad decorator that does not even return function
|
A decorator might return a function, but one that is not meaningfully associated with the undecorated function:
Listing 2. Decorator whose function ignores passed-in function
|
Finally, a better behaved decorator will in some way enhance or modify the action of the undecorated function:
Listing 3. Decorator that modifies behavior of undecorated func
>>> def addspam(fn):
... def new(*args):
... print "spam, spam, spam"
... return fn(*args)
... return new
...
>>> @addspam
... def useful(a, b):
... print a**2 + b**2
...
>>> useful(3,4)
spam, spam, spam
25
3万+



被折叠的 条评论
为什么被折叠?



