Python Class for Distances

1.7k views Asked by At

I am trying to calculate the distance between 2 points using classes

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)

However when i try to print out the CalcDist it returns an error

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

What am i doing wrong please?

3

There are 3 answers

1
Akshay On
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,M,N):
     print(math.sqrt((M.x-N.x)**2+(M.y-N.y)**2))

now in order to find distance.

>>> M.reset()
>>> N=Point(5,2)
>>> M.move(1,1)
>>> x=Point() #creating new oject
>>> x.CalcDist(M,N)

This will print distance between 2 points. For above points distance between 2 points will be 4.123105625617661

3
Constantinius On

CalcDist() is a member method of Point, so you'd have to use: M.CalcDist(N)

0
Selcuk On

You should rewrite the last line as

print(M.CalcDist(N))