Skip to content

Instantly share code, notes, and snippets.

@methane
Created December 7, 2012 06:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save methane/4231096 to your computer and use it in GitHub Desktop.
Save methane/4231096 to your computer and use it in GitHub Desktop.
__ne__ behavior
from functools import total_ordering
@total_ordering
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
__hash__ = None
def __repr__(self):
return "Point(%s, %s)" % (self.x, self.y)
def __eq__(self, other):
print("eq", self, other)
if not isinstance(other, Point):
return False
return self.x == other.x and self.y == other.y
def __lt__(self, other):
return (self.x, self.y) < (other.x, other.y)
In [1]: import point
eq Point(1, 1) Point(1, 1)
True
eq Point(1, 1) Point(1, 1)
False
eq Point(3, 2) Point(2, 3)
True
False
In [2]: x = point.Point(1,1)
In [3]: y = point.Point(1,1)
In [4]: z = point.Point(1,2)
In [5]: x == y
eq Point(1, 1) Point(1, 1)
Out[5]: True
In [6]: x != y
eq Point(1, 1) Point(1, 1)
Out[6]: False
In [7]: x == z
eq Point(1, 1) Point(1, 2)
Out[7]: False
In [8]: x != z
eq Point(1, 1) Point(1, 2)
Out[8]: True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment