python通过装饰器检查函数参数数据类型的方法
作者:niuniu 时间:2022-07-22 14:11:08
本文实例讲述了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')
希望本文所述对大家的Python程序设计有所帮助。
标签:python,装饰器,方法
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python for循环赋值问题
2023-01-26 05:56:32
Django 拆分model和view的实现方法
2022-03-28 02:35:34
![](https://img.aspxhome.com/file/2023/5/80595_0s.jpg)
python numpy存取文件的方式
2021-04-15 18:31:56
![](https://img.aspxhome.com/file/2023/2/96932_0s.png)
Python连接SQLServer2000的方法详解
2023-07-23 09:02:12
ASP编程中的常见问题
2007-09-20 13:32:00
Python 中 -m 的典型用法、原理解析与发展演变
2023-07-09 17:11:40
![](https://img.aspxhome.com/file/2023/0/87550_0s.jpg)
Python爬虫简单运用爬取代理IP的实现
2021-08-25 23:26:42
![](https://img.aspxhome.com/file/2023/1/75201_0s.jpg)
如何基于Python深度图生成3D点云详解
2022-03-08 16:41:11
![](https://img.aspxhome.com/file/2023/5/96915_0s.png)
Python3爬取英雄联盟英雄皮肤大图实例代码
2022-05-20 23:40:55
![](https://img.aspxhome.com/file/2023/5/83935_0s.png)
基于循环神经网络(RNN)实现影评情感分类
2021-11-27 16:42:10
python 使用tkinter+you-get实现视频下载器
2023-08-15 18:40:25
![](https://img.aspxhome.com/file/2023/0/81560_0s.png)
asp如何获知Connection对象更多的信息?
2009-11-23 20:53:00
Pycharm最全报错的原因与解决方法总结(推荐!)
2023-10-26 04:20:03
![](https://img.aspxhome.com/file/2023/4/79534_0s.jpg)
FCKeditor 编辑器实战技巧 Ⅰ
2008-10-08 10:22:00
![](https://img.aspxhome.com/file/uploadpic/20071/200713110656772.gif)
asp如何限制重复订阅邮件或重复投票?
2010-06-09 18:48:00
浅淡BANNER设计
2010-09-25 18:37:00
![](https://img.aspxhome.com/file/UploadPic/20109/25/02-33s.jpg)
Oracle数据库性能优化技术开发者网络Oracle
2010-07-18 13:05:00
Django框架教程之正则表达式URL误区详解
2021-03-18 13:46:13
![](https://img.aspxhome.com/file/2023/3/90583_0s.png)
5个提高你站点可读性的方法
2011-01-31 17:48:00
![](https://img.aspxhome.com/file/UploadPic/20111/31/1348370-83s.jpg)
重新认识ASP之后的我在想"是时候改变了"
2008-05-08 13:10:00