Python 无法使用品脱单位装饰类方法
下面是一个非常简单的例子,试图用Pint来修饰一个类方法Python 无法使用品脱单位装饰类方法,python,pint,Python,Pint,下面是一个非常简单的例子,试图用Pint来修饰一个类方法 from pint import UnitRegistry ureg = UnitRegistry() Q_ = ureg.Quantity class Simple: def __init__(self): pass @ureg.wraps('m/s', (None, 'm/s'), True) def calculate(self, a, b): return a*b if __name__ == "_
from pint import UnitRegistry
ureg = UnitRegistry()
Q_ = ureg.Quantity
class Simple:
def __init__(self):
pass
@ureg.wraps('m/s', (None, 'm/s'), True)
def calculate(self, a, b):
return a*b
if __name__ == "__main__":
c = Simple().calculate(1, Q_(10, 'm/s'))
print c
此代码导致以下值错误
Traceback (most recent call last):
c = Simple().calculate(1, Q_(10, 'm/s'))
File "build/bdist.macosx-10.11-intel/egg/pint/registry_helpers.py", line 167, in wrapper
File "build/bdist.macosx-10.11-intel/egg/pint/registry_helpers.py", line 118, in _converter
ValueError: A wrapped function using strict=True requires quantity for all arguments with not None units. (error found for m / s, 1)
在我看来,这里的问题可能是类实例被传递给品脱装饰器。有人能找到解决方法吗?我认为错误信息非常清楚。 然而你只给出了第二个论点 您可以将第一个参数也作为
数量
给出
if __name__ == "__main__":
c = Simple().calculate(Q_(1, 'm/s'), Q_(10, 'm/s'))
print c
或者你禁用严格模式,我相信这就是你要找的
...
@ureg.wraps('m/s', (None, 'm/s'), False)
def calculate(self, a, b):
return a*b
if __name__ == "__main__":
c = Simple().calculate(1, Q_(10, 'm/s'))
print c
谢谢你的回答。保持严格模式,您的第一个答案将生成一个输出,即使第一个参数也成为一品脱量。但是,输出的单位包括包装器中指定的输出单位与第一个参数的单位的乘积,这是不正确的 解决方案只是在包装器中添加另一个“None”来说明类实例,即
@ureg.wraps('m/s', (None, None, 'm/s'), True)
def calculate(self, a, b):
return a*b