Search code examples
pythonclassmathmethodsdefinitions

Class method troubles - Python


So having some trouble with a class methods. I'll post all the information that I have. I need to write the relevant methods for the questions given.

import math
epsilon = 0.000001
class Point(object):
    def __init__(self, x, y):
        self._x = x
        self._y = y

    def __repr__(self):
        return "Point({0}, {1})".format(self._x, self._y)

First question; i need to add a method, called disttopoint that takes another point object, p, as an argument and returns the euclidean distance between the two points. I can use math.sqrt.

test cases:

abc = Point(1,2)
efg = Point(3,4)
abc.disttopoint(efg) ===> 2.8284271

Second question; add a method, called isnear that takes another point object, p, as an argument and returns True if the distance between this point and p is less than epsilon (defined in the class skeleton above) and False otherwise. Use disttopoint.

test cases:

abc = Point(1,2)
efg = Point(1.00000000001, 2.0000000001)
abc.isnear(efg) ===> True

Third question; add a method called addpoint that takes another point object p as an arguement and changes this point so that it is the sum of the oint's old value and the value of p.

test cases;

abc = Point(1,2)
efg = Point(3,4)
abc.add_point(bar)
repr(abc) ==> "Point(4,6)

Solution

  • class Point(object):
        # __init__ and __repr__ methods
        # ...
        def disttopoint(self, other):
            # do something using self and other to calculate distance to point
            # result = distance to point
            return result
    
        def isnear(self, other):
            if (self.disttopoint(other) < epsilon):
                return True
            return False