IntroGrammer IntroGrammer - 4 months ago 15x
Python Question

Python Class and List Filters

To get to the point I'm learning how to work classes and list comprehension and I'm running into this problem:

class Point:
def __init__(self, x, y):
self.x = x
self.y = y

def are_in_first_quadrant(listPoint):
newListPoint = filter(lambda pnt: pnt.x > 0 and pnt.y > 0, listPoint)
return newListPoint

pList = [Point(-3,7), Point(2,3), Point(7,0), Point(6,-9), Point(7,9)]
newList = are_in_first_quadrant(pList)

So you can see the goal of this is to spew out a list of points that are in the first quadrant, but when I try to print 'newList' I get:

[<objects.Point instance at 0x0293FA08>, <objects.Point instance at 0x0293FA80>]

Instead of:

[Point(2,3) , Point(7.9)]

Looking over this post: Filters in Python

I understand the print out is the memory location but I don't really gain much more from that.

So question is how exactly do I fix this?

I'm guessing it probably has to do with how I used lambda but again not too sure.

I'm using Python 2.7

Thanks in advance.


Also just tried

def are_in_first_quadrant(listPoint):
newListPoint = [pnt for pnt in listPoint if pnt.x > 0 and pnt.y > 0]
return newListPoint

and it throws up the same thing.


You need to provide a __repr__() method for your Point class:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return "Point({}, {})".format(self.x, self.y)

This method will be called for each element when the list is printed.

Just a remark: a function called are_... (or is_...) is supposed to return True or False. A more suitable name would be points_in_first_quadrant().

For a comparison between __str__() and __repr__(), see this question.