If you want to use a hashed Pointclass without too much work, subclass the tuple and add your own neighbor methods.
class Point(tuple):
def r_neighbor(self):
return Point((self[0] + 1, self[1]))
def l_neighbor(self):
[...]
x = Point((10, 11))
print x
print x.r_neighbor()
The tuple constructor wants iterability, so double-parens in Point((10, 11)); if you want to avoid this, you can always override __new__(overriding is __init__pointless because tuples are immutable):
def __new__(self, x, y):
return super(Point, self).__new__(self, (x, y))
This may also be the place to use modular arithmetic - although it will really depend on what you are doing:
def __new__(self, x, y, gridsize=100):
return super(Point, self).__new__(self, (x % gridsize, y % gridsize))
__new__:
def __new__(self, tup, gridsize=100):
return super(Point, self).__new__(self, (x % gridsize for x in tup))
: Point , , . defaultdict; .
from collections import defaultdict
grid = defaultdict(list)
p = Point((10, 13))
grid[(10, 13)] = [2, 3, 4]
print grid[p]
print grid[p.r_neighbor]
, dict defaultdict; defaultdict(defaultdict) ; defaultdict factory.
def intdict():
return defaultdict(int)
grid = defaultdict(intdict)
grid = defaultdict(lambda: defaultdict(int))
p = Point((10, 13))
grid[(10, 13)]["coins"] = 50
print grid[p]["coins"] # prints 50
print grid[p.r_neighbor]["coins"] # prints 0; again, no KeyError