從__contains__
文檔爲蟒蛇集意外行爲.__ 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:**如何提出問題**。明確點,用一個小例子來說明問題。正如其他人在這裏回答的,集合使用散列值,否則他們會得到列表的性能。 – bjarneh
樣式注意:使用'return self.name == other.name'而不是'if cond:return True \ n return False' – jfs