【发布时间】:2011-11-24 20:52:04
【问题描述】:
从__contains__ 文档中借用文档
print set.__contains__.__doc__
x.__contains__(y) <==> y in x.
这似乎适用于 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
那么这是一个错误还是一个功能?
【问题讨论】:
-
这个问题应该在 stackoverflow 上显示:如何提问。清楚的点,用一个小例子说明问题。正如其他人在这里回答的那样,集合使用哈希值,否则他们将获得列表的性能..
-
样式说明:使用
return self.name == other.name而不是if cond: return True \n return False