Created
April 5, 2010 03:02
-
-
Save maxp/355953 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import math | |
| class ImmutableVector(object): | |
| __slots__ = ('_d',) | |
| def __init__(self, x, y): | |
| object.__setattr__(self, _d, (x, y)) | |
| def __setattr__(self, n, v): | |
| raise ValueError("Can't alter instance of %s" % type(self)) | |
| @property | |
| def x(self): | |
| return self._d[0] | |
| @property | |
| def y(self): | |
| return self._d[1] | |
| def __eq__(self, other): | |
| return self._d == other._d | |
| def __ne__(self, other): | |
| return self._d != other._d | |
| def __hash__(self): | |
| return hash(self._d) | |
| def __add__(self, other): | |
| return type(self)(self.x+other.x, self.y+other.y) | |
| def __mul__(self, scalar): | |
| return type(self)(self.x*scalar, self.y*scalar) | |
| def __repr__(self): | |
| return '%s(%s, %s)' % (type(self).__name__, self.x, self.y) | |
| def __abs__(self): | |
| return math.hypot(self.x, self.y) | |
| #. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment