我试图让以下内容起作用,但没有成功:
我定义了自己的类型Unit(从内置类型继承float)来实现具有单位的数量的代数.它做的事情是这样的:
class Unit(float):
"""provide a simple unit converter for a given quantity"""
def __new__(cls, unit, num=1.):
return super(Unit, cls).__new__(cls, num)
def __init__(self, unit, num=1.):
"""set up base unit"""
self.unit = unit
def __str__(self,):
return '{:s} {:s}'.format(super(Unit, self).__str__(), self.unit)
def __rmul__(self, other):
print 'rmul: {:f}'.format(super(Unit, self).__rmul__(other))
return Unit(self.unit, super(Unit, self).__rmul__(other))
def to(self,target):
fun_conv = _conv(self.unit, target)
return Unit(target, num=fun_conv(self))
c = 3e8 * Unit('m/s') # this will 1) create a Unit instance with magnitude '1' and …Run Code Online (Sandbox Code Playgroud)