point class help

Steve Holden steve at holdenweb.com
Wed Jan 14 17:44:35 CET 2009


r wrote:
> 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?
> 
Not much. If you want these points to be freely mixable with containers
then you should define a function like makePoint:

def makePoint(x):
    if type(x) is Point: # assumes new-style classes
        return x
    else:
        return Point(x)

> 
> 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?

Then your __add__ method would become:

def __add__(self, other):
    other = makePoint(other)
    return (self.x+other.x, self.y+other.y)

Thous it does seem particularly perverse to have the add method not
itself return a Point.

regards
 Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC              http://www.holdenweb.com/




More information about the Python-list mailing list