python 中的@符号
周海漢 /文
2010.4.11
http://blog.csdn.net/ablo_zhou
python 2.4以后,增加了@符號修飾函數對函數進行修飾,python3.0/2.6又增加了對類的修飾。
我現在使用的python版本,支持對class的修飾:
zhouhh@zhouhh-home:~$ python
Python 2.6.4 (r264:75706, Dec? 7 2009, 18:45:15)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
@修飾符挺像是處理函數或類之前進行預處理。
?
語法示例:
@dec1
@dec2
def test(arg):
??? pass
其效果類似于
dec1(dec2(test(arg)))
修飾函數還可以帶參數。
@dec1(arg1,arg2)
def test(testarg)
效果類似于
dec1(arg1,arg2)(test(arg))
用法示例
示例1 參數類型和返回值類型檢查
對于python這樣的動態語言,不像C++這樣的一開始就有嚴格靜態的類型定義。但是,在某些情況下,就需要這樣的類型檢查,那么可以采用@修飾的方式。下面的示例就是檢查輸入參數類型和返回值類型的例子。
?
#!/usr/bin/env python#coding:utf8
def ?accepts (* types) :
????def ?check_accepts ( f) :
????????assert ?len ( types) ?== ?f. func_code. co_argcount
????????def ?new_f (* args, ?** kwds) :
????????????for ?( a, ?t) ?in ?zip ( args, ?types) :
????????????????assert ?isinstance ( a, ?t), ?/
?????????????????????? "arg %r does not match %s "?% ( a, t)
????????????return ?f(* args, ?** kwds)
????????new_f. func_name = ?f. func_name
????????return ?new_f
????return ?check_accepts
def ?returns ( rtype) :
????def ?check_returns ( f) :
????????def ?new_f (* args, ?** kwds) :
????????????result = ?f(* args, ?** kwds)
????????????assert ?isinstance ( result, ?rtype), ?/
?????????????????? "return value %r does not match %s "?% ( result, rtype)
????????????return ?result
????????new_f. func_name = ?f. func_name
????????return ?new_f
????return ?check_returns
@ accepts ( int , ?( int , float ))
@ returns (( int , float ))
def ?func ( arg1, ?arg2) :
????return ?arg1 * ?arg2
if ?__name__ == ?'__main__ ':
????a = ?func( 3 , 'asdf ')
?
zhouhh@zhouhh-home:~$ ./checktype.py
Traceback (most recent call last):
? File "./checktype.py", line 27, in <module>
??? @returns((int,float))
? File "./checktype.py", line 5, in check_accepts
??? assert len(types) == f.func_code.co_argcount
AssertionError
?
其實,xml-rpc中,對于函數參數,返回值等都需要采用xml的方式傳遞到遠程再調用,那么如何檢查類型呢?就可以用到如上的@修飾符。
?
?
總結
以上是生活随笔為你收集整理的python 中的@符号的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 电商项目前后端接口说明
- 下一篇: 易维帮助台如何“重新定义客户服务”?