View Single Post
  #1 (permalink)  
Old 01-14-2009, 03:14 PM
r
Guest
 
Posts: n/a
Default point class help

I am hacking up a point class but having problems with how to properly
overload some methods. in the __add__, __sub__, __iadd__, __isub__, I
want to have the option of passing an instance or a container(list,
tuple) like

>>> p1 = Point2d(10,10)
>>> p1 += (10,10)
>>> p1

Point2d(20,20)
>>>
>>> p2 = Point2d(10,10)
>>> p2 += p1
>>> p2

Point2d(30,30)


here is what i have, it would seem stupid to use a conditional in each
method like this...

def method(self, other):
if isinstance(other, Point2d):
x, y = origin.x, origin.y
else:
x, y = origin[0], origin[1]
#modify self.x & self.y with x&y

there must be a way to get the x, y with reusable code, i am not about
to have this conditional under every method call, What am i missing
here?


class Point2d():
def __init__(self, x, y=None):
if type(x) == tuple:
self.x = x[0]
self.y = x[1]
else:
self.x = x
self.y = y

def __str__(self):
return 'Point2d(%f, %f)' %(self.x, self.y)

def __add__(self, other):
if isinstance(other, Point2d):
x, y = origin.x, origin.y
else:
x, y = origin[0], origin[1]
return (self.x+x, self.y+y)

def __sub__(self, other):
pass

def __iadd__(self, other): #+=
pass

def __isub__(self, other): #-=
pass

any ideas?
Reply With Quote