El préstamo de la documentación de la documentación __contains__
comportamiento inesperado para un conjunto de pitón .__ contains__
print set.__contains__.__doc__
x.__contains__(y) <==> y in x.
Esto parece funcionar bien para los objetos primitivos como int, cadena base, etc, pero para los objetos definidos por el usuario que definen el __ne__
y __eq__
métodos, obtengo un comportamiento inesperado. Aquí hay un código de muestra:
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
¿Es esto un error o una característica?
esta pregunta debe ser en exhibición aquí en stackoverflow: ** cómo hacer preguntas **. claro al punto, con un pequeño ejemplo que ilustra el problema. como otros han respondido aquí, los conjuntos usan valores hash o de lo contrario obtendrían el rendimiento de las listas. – bjarneh
nota de estilo: use 'return self.name == other.name' en lugar de' if cond: return True \ n return False' – jfs