Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a Point Class in Python

I am trying to create a class in python titled "Point." I am trying to create a point on a coordinate plane x and y and track them. As well as find the distance between the points. I have to use functions and methods. I have started and here is my code. I am just not sure how to use it when I go to execute the program. Any help will be appreciated.

EDIT: Updated Code

import math


class Point(object):
    '''Creates a point on a coordinate plane with values x and y.'''

    COUNT = 0

    def __init__(self, x, y):
        '''Defines x and y variables'''
        self.X = x
        self.Y = y

    def move(self, dx, dy):
        '''Determines where x and y move'''
        self.X = self.X + dx
        self.Y = self.Y + dy

    def __str__(self):
        return "Point(%s,%s)"%(self.X, self.Y) 


    def getX(self):
        return self.X

    def getY(self):
        return self.Y

    def distance(self, other):
        dx = self.X - other.X
        dy = self.Y - other.Y
        return math.sqrt(dx**2 + dy**2)

    def testPoint(x=0,y=0):
        '''Returns a point and distance'''
        p1 = Point(3, 4)
        print p1
        p2 = Point(3,0)
        print p2
        return math.hypot(dx, dy)

    print "distance = %s"%(testPoint()) 

I still need help understanding how to actually use the code. That's why I created the testPoint function. When I actually go to execute the code in IDLE, how do I prove that everything works? Thanks a bunch guys!!

I also need to add code to the constructor to increment COUNT by 1 every time a Point object is created. I also need to add appropriate code so that points can be compared using the comparison operators while 'points' are compared based on their distance from the origin.

like image 913
xrocker15 Avatar asked Dec 11 '22 22:12

xrocker15


1 Answers

Don't forget math.hypot

def distance(self, p):
    dx = self.X - p.X
    dy = self.Y - p.Y
    return hypot(dx, dy)
like image 100
John La Rooy Avatar answered Dec 18 '22 16:12

John La Rooy