小编inv*_*and的帖子

python set .__ contains__的意外行为

借用文档中的__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 …
Run Code Online (Sandbox Code Playgroud)

python list set

9
推荐指数
2
解决办法
735
查看次数

标签 统计

list ×1

python ×1

set ×1