considerare questo frammento:Python 2: significato diverso della 'in' parola chiave per i set e liste
class SomeClass(object):
def __init__(self, someattribute="somevalue"):
self.someattribute = someattribute
def __eq__(self, other):
return self.someattribute == other.someattribute
def __ne__(self, other):
return not self.__eq__(other)
list_of_objects = [SomeClass()]
print(SomeClass() in list_of_objects)
set_of_objects = set([SomeClass()])
print(SomeClass() in set_of_objects)
che valuta a:
True
False
Qualcuno può spiegare perché il 'in' parola chiave ha un significato diverso per insiemi ed elenchi? Mi sarei aspettato che entrambi restituissero True, specialmente quando il tipo in prova ha definito i metodi di uguaglianza.
Vedere http://stackoverflow.com/questions/7549709/unexpected-behavior-for-python-set-contains .. incidentalmente, in Python 3 l'esecuzione di questo codice suggerisce che cosa sta succedendo: "TypeError: tipo non disattivabile: ' SomeClass '" – DSM
Grazie a tutti, ora è tutto chiaro. – mskel
BTW, sai che il tuo 'someattribute' qui è un attributo ** class ** e non un ** instance **, giusto? Hai * sentito * di "__init__", giusto? –