python set .__ contains__的意外行为

inv*_*and 9 python list set

借用文档中的__contains__文档

print set.__contains__.__doc__
x.__contains__(y) <==> y in x.
Run Code Online (Sandbox Code Playgroud)

这似乎适用于原始对象,如int,basestring等.但对于定义__ne____eq__方法的用户定义对象,我得到意外的行为.这是一个示例代码:

class CA(object):
  def __init__(self,name):
    self.name = name

  def __eq__(self,other):
    if self.name == other.name:
      return True
    return False

  def __ne__(self,other):
    return not self.__eq__(other)

obj1 = CA('hello')
obj2 = CA('hello')

theList = [obj1,]
theSet = set(theList)

# Test 1: list
print (obj2 in theList)  # return True

# Test 2: set weird
print (obj2 in theSet)  # return False  unexpected

# Test 3: iterating over the set
found = False
for x in theSet:
  if x == obj2:
    found = True

print found   # return True

# Test 4: Typcasting the set to a list
print (obj2 in list(theSet))  # return True
Run Code Online (Sandbox Code Playgroud)

这是一个错误或功能吗?

agf*_*agf 7

对于sets和dicts,您需要定义__hash__.任何两个相等的对象应该散列相同,以便在sets和中获得一致/预期的行为dicts.

我会建议使用_key方法,然后只是引用该你需要的地方比较项目的一部分,就像你调用__eq____ne__,而不是重新实现它:

class CA(object):
  def __init__(self,name):
    self.name = name

  def _key(self):
    return type(self), self.name

  def __hash__(self):
    return hash(self._key())

  def __eq__(self,other):
    if self._key() == other._key():
      return True
    return False

  def __ne__(self,other):
    return not self.__eq__(other)
Run Code Online (Sandbox Code Playgroud)


Joc*_*zel 2

A对其元素进行set 哈希处理以允许快速查找。您必须覆盖该__hash__方法才能找到元素:

class CA(object):
  def __hash__(self):
    return hash(self.name)
Run Code Online (Sandbox Code Playgroud)

列表不使用散列,而是像for循环一样比较每个元素。