python 中的@符號

來源:互聯網
上載者:User

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

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.