我正在尝试在需要在维度之间进行转换的情况下使用品脱,例如。液体盎司到克。
我的转换所需的值在数据库中,并且会因各种物质而变化(例如,不同液体的不同密度),所以我使用 Context.add_transformation() 方法来动态创建我的转换。这是我的测试程序:
#!/opt/env/upgrade/bin/python
import pint
ureg = pint.UnitRegistry()
c = pint.Context('ab')
def vtom(ureg, x):
# here I print some output just to see if this function is ever called
# and what arguments are passed. It is not being called.
print "vtom(%s, %s)" % (ureg, x)
# right now I just return the input, so it's 1:1. I know this is
# not right, I am just trying to get pint to find the transform and use it.
return x
c.add_transformation('[volume]', '[mass]', vtom)
ureg.add_context(c)
PQ = ureg.Quantity
# this works fine
a = PQ(1 * ureg.oz)
print '%s = %s' % (a, a.to('gram'))
b = PQ(10 * ureg.floz)
c = PQ(10 * ureg.gram)
# both these fail, see exception output below
print '%s = %s' % (c, c.to('floz'))
print '%s = %s' % (b, b.to('gram'))
输出:
1 ounce = 28.349523125 gram
Traceback (most recent call last):
File "./p.py", line 26, in <module>
print '%s = %s' % (b, b.to('gram'))
File "/opt/env/upgrade/local/lib/python2.7/site-packages/pint/quantity.py", line 332, in to
magnitude = self._convert_magnitude_not_inplace(other, *contexts, **ctx_kwargs)
File "/opt/env/upgrade/local/lib/python2.7/site-packages/pint/quantity.py", line 300, in _convert_magnitude_not_inplace
return self._REGISTRY.convert(self._magnitude, self._units, other)
File "/opt/env/upgrade/local/lib/python2.7/site-packages/pint/registry.py", line 686, in convert
return self._convert(value, src, dst, inplace)
File "/opt/env/upgrade/local/lib/python2.7/site-packages/pint/registry.py", line 1214, in _convert
return super(ContextRegistry, self)._convert(value, src, dst, inplace)
File "/opt/env/upgrade/local/lib/python2.7/site-packages/pint/registry.py", line 937, in _convert
return super(NonMultiplicativeRegistry, self)._convert(value, src, dst, inplace)
File "/opt/env/upgrade/local/lib/python2.7/site-packages/pint/registry.py", line 708, in _convert
raise DimensionalityError(src, dst, src_dim, dst_dim)
pint.errors.DimensionalityError: Cannot convert from 'fluid_ounce' ([length] ** 3) to 'gram' ([mass])
似乎品脱没有找到我的转变。在units文本文件(pint自带的默认文件)中,定义了'[volume] = [length] ** 3',所以应该可以走图找到'[mass]'..左右我想...
谢谢!