Zhou Haihan/Wen
2010.4.11
Http://blog.csdn.net/ablo_zhou
After Python 2.4, the @ symbol modifier function was added to modify the function, and the python3.0/2.6 added a modifier to the class.
I now use the Python version, which supports the modification of 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 the more information.
The @ modifier is very similar to preprocessing before a function or class is processed.
Syntax Example:
@dec1
@dec2
def test (ARG):
Pass
The effect is similar to
DEC1 (DEC2 (Test (ARG))
The modifier function can also take parameters.
@dec1 (ARG1,ARG2)
def test (Testarg)
Effect is similar to
DEC1 (ARG1,ARG2) (Test (ARG) Usage Example
Example 1 parameter type and return value type check
For dynamic languages such as Python, there is a strict static type definition in the beginning, like C + +. However, in some cases, this type of check is required, so you can use the @-decorated way. The following example is an example of checking input parameter types and return value types.
#!/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, <module>
@returns ((int,float))
File "./checktype.py", line 5, in check_accepts
Assert len (types) = = F.func_code.co_argcount
Assertionerror
In fact, in XML-RPC, for function parameters, the return value, and so on, need to be passed to the remote callback in the way of the data, then how to check the type. You can use the @ modifier as above.