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

查看:62
本文介绍了在 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!!

我还需要向构造函数添加代码,以在每次创建 Point 对象时将 COUNT 增加 1.我还需要添加适当的代码,以便可以使用比较运算符比较点,而根据它们与原点的距离比较点".

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天全站免登陆