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的方式傳遞到遠程再調用,那麼如何檢查類型呢?就可以用到如上的@修飾符。

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章