带单位的Python值
我想在Python中跟踪浮点数和整数的单位,但我不想使用像magnitude这样的外部库,因为我并不需要对这些值进行运算。我只想定义一些带有单位属性的浮点数和整数(而且我不想为这么简单的事情增加新的依赖)。我试着这样做:
class floatwithunit(float):
__oldinit__ = float.__init__
def __init__(self, *args, **kwargs):
if 'unit' in kwargs:
self.unit = kwargs.pop('unit')
self.__oldinit__(*args, **kwargs)
但是这样根本不行:
In [37]: a = floatwithunit(1.,unit=1.)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/Users/tom/<ipython console> in <module>()
TypeError: float() takes at most 1 argument (2 given)
Any suggestions?
5 个回答
1
我想你是想说
class floatwithunit(float):
而不是
def floatwithunit(float):
7
你需要重写一下 __new__
方法(这个是“真正的构造函数”,而 __init__
是“初始化器”),否则 float
的 __new__
方法会接收到多余的参数,这就是你遇到问题的原因。你不需要调用 float
的 __init__
方法(它其实什么都不做)。下面是我会这样写的代码:
class floatwithunit(float):
def __new__(cls, value, *a, **k):
return float.__new__(cls, value)
def __init__(self, value, *args, **kwargs):
self.unit = kwargs.pop('unit', None)
def __str__(self):
return '%f*%s' % (self, self.unit)
a = floatwithunit(1.,unit=1.)
print a
输出 1.000000*1.0
。
10
你可能在寻找类似这样的东西:
class UnitFloat(float):
def __new__(self, value, unit=None):
return float.__new__(self, value)
def __init__(self, value, unit=None):
self.unit = unit
x = UnitFloat(35.5, "cm")
y = UnitFloat(42.5)
print x
print x.unit
print y
print y.unit
print x + y
结果是:
35.5
cm
42.5
None
78.0