| 1 | from random import randint, random |
|---|
| 2 | import math |
|---|
| 3 | |
|---|
| 4 | class Pos(object): |
|---|
| 5 | __slots__ = ('x', 'y') |
|---|
| 6 | def __init__(self, x=0.0, y=0.0): |
|---|
| 7 | self.x = x |
|---|
| 8 | self.y = y |
|---|
| 9 | def __str__(self): |
|---|
| 10 | return '(%.1f,%.1f)' % (self.x, self.y) |
|---|
| 11 | def __repr__(self): |
|---|
| 12 | return str(self) |
|---|
| 13 | def __eq__(self, o): |
|---|
| 14 | return self.x == o.x and self.y == o.y |
|---|
| 15 | def __cmp__(self, o): |
|---|
| 16 | return self.__eq__(o) |
|---|
| 17 | def __ne__(self, o): |
|---|
| 18 | return not self.__eq__(o) |
|---|
| 19 | def __hash__(self): |
|---|
| 20 | return self.x + self.y * 10000 |
|---|
| 21 | def __lt__(self, o): |
|---|
| 22 | if self.x < o.x: |
|---|
| 23 | return True |
|---|
| 24 | if self.y < o.y: |
|---|
| 25 | return True |
|---|
| 26 | def __add__(self, o): |
|---|
| 27 | return Pos(self.x + o.x, self.y + o.y) |
|---|
| 28 | def __sub__(self, o): |
|---|
| 29 | return Pos(self.x - o.x, self.y - o.y) |
|---|
| 30 | def __div__(self, o): |
|---|
| 31 | return Pos(self.x / o, self.y / o) |
|---|
| 32 | def __mul__(self, o): |
|---|
| 33 | return Pos(self.x * o, self.y * o) |
|---|
| 34 | def __neg__(self): |
|---|
| 35 | return Pos(-self.x, -self.y) |
|---|
| 36 | # def __getitem__(self, a): |
|---|
| 37 | # if not a: return self.x |
|---|
| 38 | # return self.y |
|---|
| 39 | # def __setitem__(self, a, v): |
|---|
| 40 | # if a == 0: self.x = v |
|---|
| 41 | # if a == 1: self.y = v |
|---|
| 42 | def length(self): |
|---|
| 43 | return math.hypot(self.x, self.y) |
|---|
| 44 | def normalise(self): |
|---|
| 45 | length = math.hypot(self.x, self.y) |
|---|
| 46 | self.x = self.x / length |
|---|
| 47 | self.y = self.y / length |
|---|
| 48 | @staticmethod |
|---|
| 49 | def random(xrange,yrange): |
|---|
| 50 | return Pos(randint(xrange[0], xrange[1]), randint(yrange[0], yrange[1])) |
|---|
| 51 | @staticmethod |
|---|
| 52 | def random_range(center, max_radius): |
|---|
| 53 | a = random() * math.pi * 2 |
|---|
| 54 | r = random() * max_radius |
|---|
| 55 | return Pos(center.x + math.cos(a) * r, center.y + math.sin(a) * r) |
|---|
| 56 | @staticmethod |
|---|
| 57 | def list(l): |
|---|
| 58 | return Pos(l[0], l[1]) |
|---|
| 59 | def to_list(self): |
|---|
| 60 | return [self.x, self.y] |
|---|
| 61 | if __name__ == '__main__': |
|---|
| 62 | import timeit |
|---|
| 63 | t = timeit.Timer('b = a.y', 'from pos import Pos\na = Pos(5.3, 6.2)') |
|---|
| 64 | print min(t.repeat(5, 1000000)) |
|---|
| 65 | # getitem is 10 times slower then attribute access! |
|---|