带单位的Python值

带单位的Python值,python,Python,我需要在Python中跟踪浮点和int值上的单位,但我不想使用诸如magnity或其他外部包,因为我不需要对这些值执行操作。相反,我想要的是能够定义具有unit属性的float和int(我不想为这么简单的东西添加新的依赖项)。我试着做: class floatwithunit(float): __oldinit__ = float.__init__ def __init__(self, *args, **kwargs): if 'unit' in kwargs

我需要在Python中跟踪浮点和int值上的单位,但我不想使用诸如magnity或其他外部包,因为我不需要对这些值执行操作。相反,我想要的是能够定义具有unit属性的float和int(我不想为这么简单的东西添加新的依赖项)。我试着做:

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?
[37]中的
:a=floatwithunit(1,unit=1.)
---------------------------------------------------------------------------
TypeError回溯(最近一次调用上次)
/用户/tom/in()
TypeError:float()最多接受1个参数(给定2个)
有什么建议吗?

在尝试查看是否有标签“unit”之前,您需要检查kwargs是否为None

将代码更改为

 if kwargs and 'unit' in kwargs:
最新答复:

don't pass kwargs to __oldinit__
我想你是说

class floatwithunit(float):
而不是

def floatwithunit(float):

您需要覆盖
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu>的“构造函数本身”,否则
float
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuu。您不需要调用float的
\uuuu init\uuuu
(这是一个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

发出
1.000000*1.0

您可能正在寻找类似的内容:

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

亚历克斯·马尔泰利确实指出了问题的根源。但是,我总是觉得_; new __;非常令人困惑,因此这里有一段示例代码:

class FloatWithUnit(float):
    def __new__(cls, *args, **kwargs):
        # avoid error in float.__new__
        # the original kwargs (with 'unit') will still be passed to __init__
        if 'unit' in kwargs:
            kwargs.pop('unit')
        return super(FloatWithUnit, cls).__new__(cls, *args, **kwargs)

    def __init__(self, *args, **kwargs):
        self.unit = kwargs.pop('unit') if 'unit' in kwargs else None
        super(FloatWithUnit, self).__init__(*args, **kwargs)

谢谢-我更新了问题,因为我仍然有一个问题“记下来,”国王对陪审团说,陪审团急切地在他们的石板上写下所有三个日期,然后把它们加起来,并将答案减少到先令和便士。-爱丽丝梦游仙境-L·卡罗尔