什么是" list .__ eq __(self,other)"应该做的?

时间:2018-02-08 09:29:31

标签: python

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

我发现了这个功能:

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)

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

非常感谢:)

1 个答案:

答案 0 :(得分:2)

有问题的类似乎是list的子类,还有一些其他属性,如namestart等,并且通过调用list.__eq__(self, other),您显式调用__eq__的{​​{1}}方法(而不是子类中定义的方法)来比较这两个对象。在检查其他属性是否相等之后,这可能会比较两个列表中的内容

通常,list相当于cls.method(obj, *args)如果 obj.method(*args)obj的实例,但在这种情况下,只需调用{ {1}}(或cls)会再次调用相同的self.__eq__(other)方法,从而产生无限递归。

由于您说您来自Java:如果此类来自self == other的子类,则调用__eq__类似于调用list