Python值与单位
发布时间:2020-12-20 12:25:21 所属栏目:Python 来源:网络整理
导读:我需要在 Python中跟踪float和int值的单位,但我不想使用像scale或其他的外部包,因为我不需要对值执行操作.相反,我想要的是能够定义具有单位属性的浮点数和整数(我不想为这么简单的东西添加新的依赖关系).我试过做: class floatwithunit(float): __oldinit__
我需要在
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) 但这根本不起作用: 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? 解决方法
你可能正在寻找这样的东西:
class UnitFloat(float): def __new__(self,value,unit=None): return float.__new__(self,value) def __init__(self,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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |