def enforce(*types):
def decorator(f):
def new_f(*args, **kwds):
#we need to convert args into something mutable
newargs = []
for (a, t) in zip(args, types):
newargs.append( t(a)) #feel free to have more elaborated convertion
return f(*newargs, **kwds)
return new_f
return decorator
从Decorators for Functions and Methods:
Python 2
Python 3
在Python 3中,
func_code
已更改为__code__
,func_name
已更改为__name__
。用法:
arg2
可以是int
或float
在Python3.3上,可以使用函数注释并检查:
如果存在验证错误,则打印:
如果没有验证错误,则打印:
可以使用函数而不是lambda在断言失败中获取名称。
正如你当然知道的,仅仅根据参数的类型来拒绝它不是Python Pythonic方法相当于“先尝试处理它”
这就是为什么我宁愿做一个修饰来转换参数
这样,你的函数就有了你期望的类型 但如果参数可以像浮点数一样抖动,则可以接受
我使用这个技巧(使用适当的转换方法)来处理vectors。
我编写的许多方法都期望MyVector类具有很多功能;但是有时您只想编写
相关问题 更多 >
编程相关推荐