我需要在Python中跟踪float和int值的单位,但我不想使用像scale或其他的外部包,因为我不需要对值执行操作.相反,我想要的是能够定义具有单位属性的浮点数和整数(我不想为这么简单的东西添加新的依赖关系).我试过做:
class floatwithunit(float):
__oldinit__ = float.__init__
def __init__(self, *args, **kwargs):
if 'unit' in kwargs:
self.unit = kwargs.pop('unit')
self.__oldinit__(*args, **kwargs)
Run Code Online (Sandbox Code Playgroud)
但这根本不起作用:
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?
Run Code Online (Sandbox Code Playgroud)
你可能正在寻找这样的东西:
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
Run Code Online (Sandbox Code Playgroud)
产量:
35.5
cm
42.5
None
78.0
Run Code Online (Sandbox Code Playgroud)
你需要重写__new__(以下简称"构造正确的",而__init__是"初始化"),否则float的__new__被称为与外部参数,这是你所看到的问题的原因.你不需要调用float __init__(它是一个no-op).这是我编码的方式:
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
Run Code Online (Sandbox Code Playgroud)
发光1.000000*1.0.
| 归档时间: |
|
| 查看次数: |
314 次 |
| 最近记录: |