Неожиданное поведение для набора Python .__ содержит__
Заимствование документации у__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
Так это ошибка или фича?