python通过装饰器检查函数参数数据类型的方法
更新时间:2015年03月13日 12:02:42 作者:niuniu
这篇文章主要介绍了python通过装饰器检查函数参数数据类型的方法,涉及Python装饰器的使用技巧,具有一定参考借鉴价值,需要的朋友可以参考下
(福利推荐:【腾讯云】服务器最新限时优惠活动,云服务器1核2G仅99元/年、2核4G仅768元/3年,立即抢购>>>:9i0i.cn/qcloud)
(福利推荐:你还在原价购买阿里云服务器?现在阿里云0.8折限时抢购活动来啦!4核8G企业云服务器仅2998元/3年,立即抢购>>>:9i0i.cn/aliyun)
本文实例讲述了python通过装饰器检查函数参数数据类型的方法。分享给大家供大家参考。具体分析如下:
这段代码定义了一个python装饰器,通过此装饰器可以用来检查指定函数的参数是否是指定的类型,在定义函数时加入此装饰器可以非常清晰的检测函数参数的类型,非常方便
复制代码 代码如下:
def accepts(exception,**types):
def check_accepts(f):
assert len(types) == f.func_code.co_argcount, \
'accept number of arguments not equal with function number of arguments in "%s"' % f.func_name
def new_f(*args, **kwds):
for i,v in enumerate(args):
if types.has_key(f.func_code.co_varnames[i]) and \
not isinstance(v, types[f.func_code.co_varnames[i]]):
raise exception("arg '%s'=%r does not match %s" % \
(f.func_code.co_varnames[i],v,types[f.func_code.co_varnames[i]]))
del types[f.func_code.co_varnames[i]]
for k,v in kwds.iteritems():
if types.has_key(k) and not isinstance(v, types[k]):
raise exception("arg '%s'=%r does not match %s" % \
(k,v,types[k]))
return f(*args, **kwds)
new_f.func_name = f.func_name
return new_f
return check_accepts
def exmaple():
@accepts(Exception,a=int,b=list,c=(str,unicode))
def test(a,b=None,c=None)
print 'ok'
test(13,c=[],b='df')
def check_accepts(f):
assert len(types) == f.func_code.co_argcount, \
'accept number of arguments not equal with function number of arguments in "%s"' % f.func_name
def new_f(*args, **kwds):
for i,v in enumerate(args):
if types.has_key(f.func_code.co_varnames[i]) and \
not isinstance(v, types[f.func_code.co_varnames[i]]):
raise exception("arg '%s'=%r does not match %s" % \
(f.func_code.co_varnames[i],v,types[f.func_code.co_varnames[i]]))
del types[f.func_code.co_varnames[i]]
for k,v in kwds.iteritems():
if types.has_key(k) and not isinstance(v, types[k]):
raise exception("arg '%s'=%r does not match %s" % \
(k,v,types[k]))
return f(*args, **kwds)
new_f.func_name = f.func_name
return new_f
return check_accepts
def exmaple():
@accepts(Exception,a=int,b=list,c=(str,unicode))
def test(a,b=None,c=None)
print 'ok'
test(13,c=[],b='df')
希望本文所述对大家的Python程序设计有所帮助。
相关文章
Anaconda最新版2023安装教程Spyder安装教程图文详解
这篇文章主要介绍了Anaconda最新版2023安装教程Spyder安装教程,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2023-05-05Python中的response.text与content区别详解
这篇文章主要介绍了Python中的response.text与content区别详解,?从网络请求下来的数据,他们都是字节类型的,如果服务器不指定的话,默认编码是"ISO-8859-1",我们使用text直接拿到的是字符串类型,没有进行解码操作,则会出现乱码问题,需要的朋友可以参考下2023-12-12python Manager 之dict KeyError问题的解决
今天小编就为大家分享一篇python Manager 之dict KeyError问题的解决,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2019-12-12
最新评论