ofer simchovitch
ofer simchovitch

Reputation: 39

How to use __repr__ method python 2.7

I need to define a class of polygons in 2D. Each polygon defined by a list of tuples(coordinates) for example:

poly = [(0.5,0),(1,0.5),(0.5,1),(0,0.5)]

(There is no need for sorting) The points are sorted clockwise starting from the most left point.

My task is to define this class properly __init__, __repr__ and is_inside(self, q) function that checks weather a point is inside the polygon.

The __repr__ method supose to print '[(0.5,0),(1,0.5),(0.5,1),(0,0.5)]'

So far this is what I have:

class Polygon2D:
    def __init__(self, pts):
        for index in range(len(pts)):
            self.index = pts[index]
    def __repr__(self):

        return str(self)

When I try to run it the program crashes. Please help me!!

Upvotes: 0

Views: 1518

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121196

str(self) calls self.__str__ which will delegate to self.__repr__ which in your implementation calls str(self), starting the whole circle again. So yes, you caused an infinite recursion.

Your more immediate problem is storing the pts list however. You are only ever storing the last point, discarding the rest. Assigning to self.index in a loop only results in the last assignment winning.

Just store pts directly, as an attribute, and simply turn that into a string as the result for __repr__:

class Polygon2D:
    def __init__(self, pts):
        self.points = pts

    def __repr__(self):
        return str(self.points)

Storing the whole list of points will also make implementing your is_inside function achievable.

Upvotes: 4

Related Questions