point class help

Matimus mccredie at gmail.com
Wed Jan 14 20:59:48 CET 2009


On Jan 14, 8:50 am, r <rt8... at gmail.com> wrote:
> On Jan 14, 10:44 am, Steve Holden <st... at holdenweb.com> wrote:
>
> > Thous it does seem particularly perverse to have the add method not
> > itself return a Point.
>
> Thanks Steve,
> i was going implement exactly this but thought there "might" be a
> better way i did not know about. So i feel better about myself
> already. And your right, i should be returning a Point2d()
> Many Thanks

I just inherited from tuple and did it like this. Note that this
served my needs, but it definitely needs some work to become general
purpose. Also note that I used '__new__' instead of __init__, making
this type immutable.

class Point(tuple):
    "Simple immutable point class (vector) supports addition and
subtraction"

    def __new__(cls, x, y=None):
        if y is None:
            x, y = x
        return super(Point, cls).__new__(cls,(x, y))

    def __add__(self, p):
        return Point(self[0]+p[0], self[1]+p[1])

    def __sub__(self, p):
        return Point(self[0]-p[0], self[1]-p[1])

    def __neg__(self):
        return Point(-self[0], -self[1])

    def __pos__(self):
        return self

    def __str__(self):
        return "Point(%d, %d)"%(self[0], self[1])

    __repr__ = __str__



Matt



More information about the Python-list mailing list