How to get the values of instances using classes?

Question:

i’am new into classes in python. And i’am running into an error, so i wanted to calculate the distance between two coordinates. But i’am struggling to get the values x and y values from p1 and p2 or p2 and p3,… And to use theses values in a method for calculate the distance between the 2 given coordinates.

import math
class Point:
   def __init__(self, x, y):
       self.x = x
       self.y = y

   def print(self):
       i = (self.x, self.y)
       print(tuple(i))
       return self

   def reflect_x(self):
       self.y*=-1
       return self

   def distance(self):
       # x2, and x1 are gotten by the passed values from p1 or p2 or p3
       dist = math.sqrt( (x2 - x1)**2 + (y2 - y1)**2 )
       return dist

p1 = Point(1,4)
p2 = Point(-3,5)
p3 = Point(-3,-5)

print(p1.distance())
print(p2.distance(p3))
print(p3.distance(p2))

Thanks in advance <3

Asked By: SiBMs

||

Answers:

You have to pass the second point as an argument to the distance method. Then you can access the x and y attributes of the two points self and other.

def distance(self, other):
     dist = math.sqrt( (other.x - self.x)**2 + (other.y - self.y)**2 )
     return dist


print(p1.distance())  # Error, missing argument. You need two points to define a distance.
print(p1.distance(p2))  # Distance between p1 and p2
print(p3.distance(p2)  # Distance between p3 and p2

(You could let other take a default value of None, and of other is None, then just return 0. I’m not sure there is a great need to compute the trivial distance between a point and itself, though.)


As an aside, you can use the built-in complex type to manipulate two-dimensional points.

def distance(self, other):
    p1 = complex(self.x, self.y)
    p2 = complex(other.x, other.y)
    return abs(p1 - p2)
Answered By: chepner
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.