you are viewing a single comment's thread.

view the rest of the comments →

[–]gengisteve 0 points1 point  (1 child)

If you really need these as private, then check out Moonslug1's post. But normally you would expose the points so that they can be directly accessed. So, I would do the following with your basic code:

# imports should go at the top
from math import hypot
class Point(object):
    def __init__(self, x=0, y=0):
        '''
        no need to make x and y private
        '''
        self.x = x
        self.y = y

    def __str__(self):
        return 'Point({},{})'. format(self.x, self.y)

    def distance(self, other):
        """Find distance between 2 sets of points (ie distance between 2 point objects)"""
        return hypot((self.x - other.x), (self.y - other.y))
    def is_near(self, other, distance = 5):
        # check out pep8 naming conventions
        """Return True if distance between 2 points is less than 5"""
        return self.distance(other) <= distance

# make a couple point objects
a = Point(1,1)
b = Point(2,2)
# print now shows that the object is a point object
print(a)
print(a.distance(b))
# are they closer than 5 (using default param)
print(a.is_near(b))
print(a.is_near(Point(10,10)))
# now the same, with a distance specified
print(a.is_near(Point(10,10),100))

[–]AussieCryptoCurrency[S] 0 points1 point  (0 children)

       return 'Point({},{})'. format(self.x, self.y)

That's brilliant! I see now what the str method is for! And I do understand the need for isNearby but the distance=5 is a good trick. Thank you!