在Python中创建点类 [英] Making a Point Class in Python

查看:900
本文介绍了在Python中创建点类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在python中创建一个名为Point的类。我试图在坐标平面x和y上创建一个点并跟踪它们。以及找到点之间的距离。我必须使用函数和方法。我已经开始,这里是我的代码。我只是不知道如何使用它,当我去执行程序。任何帮助将不胜感激。

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.

编辑:更新代码

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()) 

理解如何实际使用代码。这就是为什么我创建了 testPoint 函数。当我真的去在IDLE中执行代码,我如何证明一切正常?感谢一群人!

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!!

我还需要添加代码到构造函数中,每次将 COUNT 增加1创建一个Point对象。我还需要添加适当的代码,使得点可以使用比较运算符进行比较,而点根据它们与原点的距离进行比较。

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.

推荐答案

不要忘记 math.hypot

def distance(self, p):
    dx = self.X - p.X
    dy = self.Y - p.Y
    return hypot(dx, dy)

这篇关于在Python中创建点类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆