python如何定义带参数的装饰器
作者:北门吹雪 时间:2022-01-07 04:18:30
本文实例为大家分享了python定义带参数装饰器的具体代码,供大家参考,具体内容如下
案例:
实现一个装饰器,用它来检查被装饰函数的参数类型。
需求:
装饰器可以通过函数,指明函数参数类型,进行函数调用的时候,传入参数,检测到不匹配时,抛出异常
如何解决这个问题?
先要获取函数的签名,并且获得装饰器中参数,然后把函数签名和装饰器中参数对应绑定
把调用函数时候传入的参数和函数签名进行绑定
把实参和装饰器中定义的数据进行类型比较,不匹配抛出异常
#!/usr/bin/python3
from inspect import signature
def check_type(*ty_args, **ty_kwargs):
def out_wrapper(func):
# 通过signature方法,获取函数形参:name, age, height
sig = signature(func)
# 获得装饰器传来的参数, 函数签名与之绑定,字典类型
bind_types = sig.bind_partial(*ty_args, **ty_kwargs).arguments
print(bind_types)
def wrapper(*args, **kwargs):
# 给执行函数中具体的实参进行和形参进行绑定,形成字典的形式
func_type = sig.bind(*args, **kwargs).arguments.items()
print(func_type)
# 循环形参和实参字典的items()形式
for name, obj in func_type:
if name in bind_types:
if not isinstance(obj, bind_types[name]):
raise TypeError('%s must be %s' % (name, bind_types[name]))
func(*args, **kwargs)
return wrapper
return out_wrapper
# 通过装饰器实现对函数参数进行类型检查
@check_type(str, int, float)
def func(name, age, height):
print(name, age, height)
if __name__ == '__main__':
func('bei_men', 18, 1.75)
来源:http://www.cnblogs.com/2bjiujiu/p/7291819.html
标签:python,参数,装饰器
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
PHP children()函数讲解
2023-06-13 04:38:38
![](https://img.aspxhome.com/file/2023/9/55409_0s.png)
DNS优化的原理和方法
2012-04-26 16:43:56
python实现打砖块游戏
2023-11-09 21:27:15
如何创建SQL Server 2000故障转移群集
2009-02-13 17:18:00
SQL语句之WHERE子句的使用方法
2007-08-11 12:25:00
Python笔试面试题小结
2022-07-17 12:51:23
php实现压缩多个CSS与JS文件的方法
2023-11-23 08:39:59
有关缓存 Cache 的随想
2008-06-09 14:25:00
![](https://img.aspxhome.com/file/UploadPic/20086/9/200869143245569s.jpg)
纯ASP结合VML生成完美图-饼图
2010-05-11 16:49:00
Opencv实现二维直方图的计算及绘制
2023-07-18 23:34:52
![](https://img.aspxhome.com/file/2023/6/59646_0s.jpg)
sqlserver中获取月份的天数的方法分享
2011-09-30 11:27:52
Java使用正则表达式验证用户名和密码的方法
2023-06-13 18:05:56
python使用socket向客户端发送数据的方法
2023-08-13 00:16:51
Go-ethereum 解析ethersjs中产生的签名信息思路详解
2023-08-05 21:34:49
![](https://img.aspxhome.com/file/2023/7/87617_0s.jpg)
ASP 禁用清除页面缓存
2008-07-21 12:43:00
Oracle数据库的备份与恢复
2010-07-28 12:52:00
python生成指定长度的随机数密码
2021-01-24 23:53:17
在JScript中使用RecordSet对象的GetRows方法
2008-01-16 13:12:00
asp简单可逆运算字符串加密解密函数
2010-05-04 16:42:00
Go语言快速入门图文教程
2023-07-23 10:30:16
![](https://img.aspxhome.com/file/2023/7/95367_0s.jpg)