用于距离的Python类

时间:2014-03-17 09:31:16

标签: python

我正在尝试使用类

计算2点之间的距离
import math

class Point:

    #This initializes our class and says that if x,y co-ords are not given then
    #the default is x=0, y=0
    def __init__(self,x=0,y=0):
        self.move(x,y)

    #move the point to a new location in 2D space
    def move(self,x,y):
        self.x=x
        self.y=y

    #reset the point back to the origin
    def reset(self):
         self.move(0,0)

    #This will find the distance between the 2 points
    def CalcDist(self,otherpoint):
        return math.sqrt((self.x-otherpoint.x)**2+(self.y-otherpoint.y)**2)

但是,当我尝试打印CalcDist时,它会返回错误

>>> M=Point()
>>> M.reset()
>>> N=Point(5,2)
>>> M.move(1,1)
>>> print(CalcDist())
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    print(CalcDist())
NameError: name 'CalcDist' is not defined

请问我做错了什么?

2 个答案:

答案 0 :(得分:2)

CalcDist()Point的成员方法,因此您必须使用:M.CalcDist(N)

答案 1 :(得分:0)

您应该将最后一行重写为

print(M.CalcDist(N))