您的位置:首页 > 编程语言 > Python开发

python中'@'符号用作函数修饰符

2008-08-24 14:10 267 查看
'@'符号用作函数修饰符是python2.4新增加的功能,修饰符必须出现在函数定义前一行,不允许和函数定义在同一行。也就是说 @A def f(): 是非法的。 只可以在模块或类定义层内对函数进行修饰,不允许修修饰一个类。 一个修饰符就是一个函数,它将被修饰的函数做为参数,并返回修饰后的同名函数或其它可调用的东西。
请看以下实例:
>>> 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
>>> def spamdef(fn):
...     print "spam, spam, spam"
...
>>> @spamdef
... def useful(a, b):
...     print a**2 + b**2
...
spam, spam, spam
>>> useful(3, 4)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'NoneType' object is not callable
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
>>> 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
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐