Skip to content

Instantly share code, notes, and snippets.

@UBarney
Created September 6, 2017 14:35
Show Gist options
  • Save UBarney/266600b1ad05bf9ec6d60aecb47934f4 to your computer and use it in GitHub Desktop.
Save UBarney/266600b1ad05bf9ec6d60aecb47934f4 to your computer and use it in GitHub Desktop.
python 装饰器
# coding=utf-8
# 详细语法说明见 https://www.python.org/dev/peps/pep-0318/#current-syntax
# 通过装饰器能够获取到调用函数的参数,函数执行的返回值,能够直接运行所装饰的函数
def checkType(*acceptedType): # 检查传入函数的参数类型
print 'calling checkType with %s'%str(acceptedType)
def warpper(fun): ## fun为下一个要执行的函数,可以把fun(fun1(fun2...))看作整体
print fun.__name__
def anotherFun(*calledArgs): ## 最外层函数的参数 此处为 传入a的参数
print calledArgs ##
for i,j in zip(acceptedType, calledArgs):
assert type(j)==i,\
'调用 %s 时传入的参数 %s 类型不正确'%(str(fun.__name__),str(j))
return fun(*calledArgs)
return anotherFun
return warpper
def ckeckReturn(acceptedReturnType):
'''
检查被装饰函数的返回类型
:param acceptedReturnType: 调用此装饰器的参数
:return:
'''
print 'calling ckeckReturn with %s'%str(acceptedReturnType)
def handleFun(f): # 接受调用的函数
def _checkReturn(*args): # 接受调用函数的参数
result=f(*args)
for i,j in zip(result, acceptedReturnType):
assert type(i)==j
return _checkReturn
return handleFun
@checkType(int,str)
@ckeckReturn((str,int))
def a(x,b):
return b,x
a(1,'1')
a(1,90)
a('20','2')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment