本文介绍了Python集合([])如何检查两个对象是否相等?对象需要定义什么方法来自定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Python中创建一个'container'对象或类,它保存我也定义的其他对象的记录。该容器的一个要求是,如果两个对象被认为是相同的,则删除一个(任一个)。我的第一个想法是使用 set([])作为包含对象,完成这个要求。

I need to create a 'container' object or class in Python, which keeps a record of other objects which I also define. One requirement of this container is that if two objects are deemed to be identical, one (either one) is removed. My first thought was to use a set([]) as the containing object, to complete this requirement.

但是,集合不会删除两个相同的对象实例之一。我必须定义什么才能创建一个?

However, the set does not remove one of the two identical object instances. What must I define to create one?

这是Python代码。

Here is the Python code.

class Item(object):
  def __init__(self, foo, bar):
    self.foo = foo
    self.bar = bar
  def __repr__(self):
    return "Item(%s, %s)" % (self.foo, self.bar)
  def __eq__(self, other):
    if isinstance(other, Item):
      return ((self.foo == other.foo) and (self.bar == other.bar))
    else:
      return False
  def __ne__(self, other):
    return (not self.__eq__(other))

翻译 b
$ b

Interpreter

>>> set([Item(1,2), Item(1,2)])
set([Item(1, 2), Item(1, 2)])
It is clear that __eq__(), which is called by x == y, is not the method called by the set. What is called? What other method must I define?

注意: Item 必须保持可变,并且可以更改,因此我无法提供 __哈希__() 方法。如果这是唯一的方法,那么我将重写使用不可变的 Item

Note: The Items must remain mutable, and can change, so I cannot provide a __hash__() method. If this is the only way of doing it, then I will rewrite for use of immutable Items.

推荐答案

我恐怕你必须提供一个 __哈希__()方法。但是你可以用它的方式编码,它不依赖于你的 Item 的可变属性。

I am afraid you will have to provide a __hash__() method. But you can code it the way, that it does not depend on the mutable attributes of your Item.

这篇关于Python集合([])如何检查两个对象是否相等?对象需要定义什么方法来自定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 11:23