2

这是一个非常简单的示例,旨在使用 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__ == "__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)

在我看来,这里的问题可能是类实例被传递给品脱装饰器。有人有解决这个问题的方法吗?

4

2 回答 2

1

我认为错误信息很清楚。在严格模式下,所有参数都必须给出,Quantity 但你只给出第二个参数。

您要么将第一个参数作为 a Quantitytoo

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
于 2016-09-13T04:50:00.800 回答
1

感谢你的回答。保持严格模式,您的第一个答案会产生一个输出,即将第一个参数也设为品脱数量。但是,输出的单位包括包装器中指定的输出单位和第一个参数的单位的乘积,这是不正确的。

解决方案只是在包装器中添加另一个“无”以说明类实例,即

@ureg.wraps('m/s', (None, None, 'm/s'), True)
def calculate(self, a, b):
    return a*b
于 2016-09-13T19:16:58.907 回答