【问题标题】:Approximately compare decimal attributes of a class defined with `attrs`大致比较用`attrs`定义的类的十进制属性
【发布时间】:2020-05-08 21:30:29
【问题描述】:

我有一个带有浮点 x 属性的 Thing 类。我想大致比较Thing 的两个实例,相对容差为 1e-5。

import attr

@attr.s
class Thing(object):
    x: float = attr.ib()


>>> assert Thing(3.141592) == Thing(3.1415926535)  # I want this to be true with a relelative tolerance of 1e-5
False

我是否需要重写 __eq__ 方法,或者是否有一种简洁的方式告诉 attr 使用 math.isclose() 或自定义比较函数?

【问题讨论】:

    标签: python-attrs


    【解决方案1】:

    是的,设置eq=True 并实现您自己的__eq__/__ne__ 是您要走的路。在这种情况下,您的需求是如此具体,以至于我什至不知道如何将其抽象出来而不造成混淆。

    【讨论】:

    • 在某种程度上,比较floats 是否相等应该总是有一定的容忍度。最好有一个attrs 配置/设置来指定浮点数应该总是这样比较。是否可以为一个字段指定__eq__
    • 还没有,。但我们正在努力:github.com/python-attrs/attrs/pull/627
    猜你喜欢
    • 1970-01-01
    • 2016-08-15
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    • 2010-12-25
    • 1970-01-01
    相关资源
    最近更新 更多