python中'@'符号用作函数修饰符
2008-08-24 14:10
267 查看
'@'符号用作函数修饰符是python2.4新增加的功能,修饰符必须出现在函数定义前一行,不允许和函数定义在同一行。也就是说 @A def f(): 是非法的。 只可以在模块或类定义层内对函数进行修饰,不允许修修饰一个类。 一个修饰符就是一个函数,它将被修饰的函数做为参数,并返回修饰后的同名函数或其它可调用的东西。
请看以下实例:
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 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 |
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 |
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
相关文章推荐
- error C2061: syntax error : identifier 'SHFILEINFOW' // 无法解析的外部符号 wWinMain,该符号在函数 WinMainCRTStartup
- python的operator.itemgetter('click')用于定义获取'click'项的函数
- python文件中的__name__=='__main__'的使用及调用其他py文件中的函数方法
- python中if __name__ == '__main__': 的解析
- python出现Non-ASCII character '\xe7' in file ex6.py on line 1, but no encoding declare错误
- Python的help()中,"->"符号和"<==>"符号的含义
- 【Python】【解决】UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 1: ordinal not in r
- python3 -> 函数注释 Function Annotations
- 【LeetCode with Python】 Pascal's Triangle
- 在php中的变量和函数名前加&符号的意思
- kingofark's Ineffective C/C++:自白2:有符号、无符号还有位运算,我的天!
- Python中的函数修饰符@
- 180202—【Python 初识 D9】Python的内建函数 & 工厂函数
- vs2010 库函数问题:objidl.h(11266) : error C2061: syntax error : identifier '__RPC__out_xcount_part'
- Python 去除List的回车'/n'
- extern "c" 动态链接库符号表导出问题 以及函数参数压栈顺序
- sql 语句 写一个函数T-sql函数elimination(a,b)将出现在第一个字符串中的第二个字符串中的所有字符删除,即:select dbo.elimination('abcdefg123
- Python之'\r'
- 1>E1400Dlg.obj : error LNK2019: 无法解析的外部符号 __imp__Demo@12,该符号在函数 "protected: v
- Python:[转]IOError: [Errno 22] invalid mode ('r') or filename: