无法使用 Pint 个单位修饰 class 方法
Unable to decorate a class method using Pint units
这是一个非常简单的示例,它试图使用 Pint、
修饰 class 方法
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
此代码导致以下 ValueError。
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)
在我看来,这里的问题可能与 class 个实例被传递给 pint 装饰器有关。谁有解决此问题的解决方案?
我认为错误信息很清楚。 In strict mode all arguments have to be given as Quantity
然而你只给出了第二个参数。
您也可以将第一个参数作为 Quantity
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
感谢您的回答。保持严格模式,您的第一个答案会产生一个输出,即将第一个参数设为 pint 数量。但是,输出的单位包括包装器中指定的输出单位与第一个参数的单位的乘积,这是不正确的。
解决方案只是向包装器添加另一个 'None' 以说明 class 实例,即
@ureg.wraps('m/s', (None, None, 'm/s'), True)
def calculate(self, a, b):
return a*b
这是一个非常简单的示例,它试图使用 Pint、
修饰 class 方法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
此代码导致以下 ValueError。
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)
在我看来,这里的问题可能与 class 个实例被传递给 pint 装饰器有关。谁有解决此问题的解决方案?
我认为错误信息很清楚。 In strict mode all arguments have to be given as Quantity
然而你只给出了第二个参数。
您也可以将第一个参数作为 Quantity
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
感谢您的回答。保持严格模式,您的第一个答案会产生一个输出,即将第一个参数设为 pint 数量。但是,输出的单位包括包装器中指定的输出单位与第一个参数的单位的乘积,这是不正确的。
解决方案只是向包装器添加另一个 'None' 以说明 class 实例,即
@ureg.wraps('m/s', (None, None, 'm/s'), True)
def calculate(self, a, b):
return a*b