Skip to main content
 首页 » 编程设计

python之无法使用品脱单位装饰类方法

2024年10月17日8cyq1162

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

在我看来,这里的问题可能与传递给品脱装饰器的类实例有关。谁能提供解决此问题的解决方案?

请您参考如下方法:

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

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

@ureg.wraps('m/s', (None, None, 'm/s'), True) 
def calculate(self, a, b): 
    return a*b