python - "list.__eq__(self, other)"应该做什么?

标签 python

我是一个Python新手,昨天我不得不深入研究 Graphite 网络开源项目的源代码。但我的问题并不是专门针对 Graphite 。

我发现了这个功能:

def __eq__(self, other):
  if not isinstance(other, TimeSeries):
    return False

  if hasattr(self, 'color'):
    if not hasattr(other, 'color') or (self.color != other.color):
      return False
  elif hasattr(other, 'color'):
    return False

  return ((self.name, self.start, self.end, self.step, self.consolidationFunc, self.valuesPerPoint, self.options, self.xFilesFactor) ==
  (other.name, other.start, other.end, other.step, other.consolidationFunc, other.valuesPerPoint, other.options, other.xFilesFactor)) and list.__eq__(self, other)

我明白这个方法应该做什么(我来自java世界,这很熟悉)。我的审问是关于这个样本的,最后:

list.__eq__(self, other)

它为什么在这里以及它应该做什么?

非常感谢:)

最佳答案

相关类似乎是 list 的子类,具有一些附加属性,例如 namestart 等,通过调用 list.__eq__(self, other),您可以显式调用 list__eq__ 方法(而不是子类中定义的方法) )来比较两个对象。在检查两个列表的其他属性是否相等后,这可能会比较两个列表的内容

通常,cls.method(obj, *args) 等价于 obj.method(*args)if objcls 的一个实例,但在这种情况下,只需调用 self.__eq__(other) (或 self == other >) 会再次调用相同的 __eq__ 方法,从而导致无限递归。

既然你说你来自Java:假设这个类来自list的子类,调用list.__eq__(self, other) 类似于调用 super.equals(other)

关于python - "list.__eq__(self, other)"应该做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48681960/

相关文章:

python - Python 的处理能力

Python 在绘图中使用自定义颜色

python - (已关闭)康威的生命游戏未正确更新(Python)

python - 在Python中生成特定的列表组合

python - if 语句范围内的值不打印(Python 中的 Runge-Kutta 四阶)

python - Flask Python 日志记录 : TypeError while logging file path in File

Python .aspx 搜索表单结果问题

python - 通过计算变换计算元素位置

python - 在python中 reshape 图像矩阵

python - 遍历 Web 元素