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的方式传递到远程再调用,那么如何检查类型呢?就可以用到如上的@修饰符。

 

 

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值