2

我在项目中使用pint模块。我项目中的对象将数字数据处理为小数。当我将简单的品脱单位设置为小数时,它可以工作:

>>> import pint
>>> from decimal import Decimal as D
>>> ureg = pint.UnitRegistry()
>>> D(10) * ureg.kN
<Quantity(10, 'kilonewton')>

但是,如果我尝试添加第二个单元,它就会中断。在此示例中构建千牛顿*米:

>>> D(10) * ureg.kN * ureg.m
TypeError: unsupported operand type(s) for *: 'decimal.Decimal' and 'float'

我正在使用这个黑客:

>>> a = D(1) * ureg.kN
>>> b = D(1) * ureg.m
>>> unit_kNm = a * b
>>> D(10) * unit_kNm
<Quantity(10, 'kilonewton * meter')>

我明白为什么会这样。我正在寻找一种解决方案来设置我想要的品脱。

4

2 回答 2

3

这有效:

>>> D(10) * (ureg.kN * ureg.m)
<Quantity(10, 'kilonewton * meter')>

这也是:

>>> Q = ureg.Quantity
>>> Q(D(10), "kN*m")
<Quantity(10, 'kilonewton * meter')>
于 2017-07-10T13:09:52.683 回答
1

类型转换为decimal

import decimal
D(10) * ureg.kN * decimal.Decimal(ureg.m)
于 2017-07-10T12:11:20.700 回答