Ich versuche set().issubset()
zum Vergleich der Sequenzen zu verwenden. Wie Sie sich vorstellen können, funktioniert es nicht wie erwartet;) Im Voraus: Entschuldigung für den langen Code-Blob.Python set(). Issubset() funktioniert nicht wie erwartet
class T(object):
def __init__(self, value, attributes = None):
self.value = value
self.attributes = Attributes(attributes)
def __eq__(self, other):
if not isinstance(other, T):
return False
if self.value == other.value and self.attributes == other.attributes:
return True
else:
return False
def __ne__(self, other):
if not isinstance(other, T):
return True
if self.value != other.value or self.attributes != other.attributes:
return True
else:
return False
class Attributes(dict):
def __init__(self, attributes):
super(dict, self)
self.update(attributes or dict())
def __eq__(self, other):
if self.items() == other.items():
return True
else:
return False
def __ne__(self, other):
if not self.items() == other.items():
return True
else:
return False
def __cmp__(self, other):
return self.items().__cmp__(other.items())
x = [T("I", {'pos': 0}), T("am", {'pos': 1}), T("a", {'pos': 2}), T("test", {'pos': 3})]
y = [T("a", {'pos': 2}), T("test", {'pos': 3})]
xx = set(x)
yy = set(y)
assert y[0] == x[2], "__eq__ did fail, really?" #works
assert y[1] == x[3], "__eq__ did fail, really?" #works
assert xx-(yy-xx) == xx, "set subtract not working" #works, but is nonsense. see accepted answer
assert not xx.issubset(yy), "i am doing it wrong..." #works
assert yy.issubset(xx), "issubset not working :(" #FAILS!
oben Code schlägt fehl, die letzte Behauptung:
$ python
Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import issubsettest
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "issubsettest.py", line 52, in <module>
assert yy.issubset(xx), "issubset not working :("
AssertionError: issubset not working :(
>>>
Was ich hier fehlt?
Ich denke, dass dies, weil Benutzer –
Ich denke, das Problem ist, dass Ihre Klasse 'T' überschreibt die Methode' __hash__'. Siehe [Dokumentation] (http://docs.python.org/reference/datamodel.html#object.__hash__): * Wenn es __cmp __() oder __eq __() aber nicht __hash __() definiert, sind seine Instanzen nicht verwendbar in Hash-Sammlungen.* – halex
Ich habe gerade Ihren Code mit Python 3.3 getestet, was den Fehler gibt: 'TypeError: nicht hashbarer Typ: 'T'' in der Zeile' xx = set (x) 'also ist es definitiv das Fehlen von' __hash__'. – halex