pythonic比较复合类的方法?

时间:2009-04-06 19:07:56

标签: python

我有一个充当树中项目的类:

class CItem( list ):
  pass

我有两棵树,每棵树都以CItem为根,每个树项都有一些dict成员(比如item._test = 1)。现在我需要比较这些树。我可以建议为CItem重载一个比较运算符:

class CItem( list ):
  def __eq__( self, other ):
    # first compare items as lists
    if not list.__eq__( self, other ): return False
    # now compare dict members
    if self.__dict__ != other.__dict__: return False
    # seems equal
    return True

现在我可以使用'=='或'!='来比较两棵树。这是一种“pythonic”方式还是这样的比较可以轻松完成?

1 个答案:

答案 0 :(得分:3)

我的感觉就像

class CItem(list):
    def __eq__(self, other):
        return list.__eq__(self, other) and self.__dict__ == other.__dict__

但它基本上与您拥有的代码相同,只是用较短的符号表示。我想不出任何更实质性的改变,随便做。

相关问题