Python Advanced Programming Decorator 02

Source: Internet
Author: User

#装饰器02

#参数检查

#主要是用在接收或者返回函数, may be useful when executing in a specific context

#例如: There is a function called by XML-RPC, and Python will not be able to provide its full signature directly as in a static class language, which is required when the XML-RPC customer requires a function signature.

"""

XML-RPC Related learning: Http://zh.wikipedia.org/wiki/XML-RPC

"""

#装饰器能提供这种签名类型 and make sure that the input and output are related to this, as follows

From itertools Import *

rpc_info={}

def xml_rpc (in_= (), out= (Type (None),)):

def _xml_rpc (function):

#注册签名

Func_name=function.func_name

rpc_info[func_name]= (In_,out)

def _check_type (ele,types):

"" "Subfybctuib tgat Cgecjs tge Types" ""

If Len (ele)!=len (types):

Raise TypeError (' argument count is wrong ')

Typed=enumerate (Izip (ele,types))

For index,couple in typed:

Arg,of_right_type=couple

If Isinstance (arg,of_right_type):

Continue

Raise TypeError (' arg #%d should be%s '% (Index,of_right_type))

#封装函数

def __xml_rpcs (*args): #没能允许关键字

#检查输入的内容

Checkable_atrgs=args[1:] #removing Self

_check_type (Checkable_atrgs,in_)

#执行函数

Res=function (*args)

#检查输出内容

If not type (res) in (tuple,list):

Checkable_atrgs= (res,)

Else

Checkable_atrgs=res

_check_type (Checkable_atrgs,out)

#函数及其类型检查成功

return res

Return __xml_rpcs

Return _XML_RPC

#装饰器将该函数注册到全局字符中, and save a list of the types for its parameters and return values, note that LYYNWBIOVWDT is a great simplification,

#例子;

Class R (object):

@xml_rpc (int,int) #two int--none

def meth1 (self,int1=1,int2=1):

print ' received%d and%d '% (INT1,INT2)

@xml_rpc ((str,), (int,)) #string--int

def meth2 (self,phrease):

print ' received%s '% (phrease)

Return 12

Print rpc_info#{' Meth12 ': (<type ' int ';, <type ' int ' >), ' Meth2 ': ((<type ' str;,), (<type ' int ' > ,))}

My1=r ()

My1.meth1 (ON)

My1.meth2 (2)

This example has a problem, if you see a friend, help me to point out, in this first thank you

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.