import math
class point:
def __init__(self,p1,p2):
self.p1 = p1
self.p2 = p2
def distancepoint(self):
x1,y1 = self.p1
x2,y2 = self.p2
distance = math.sqrt((x1-x2)**2 + (y1-y2)**2)
return distance
p1 = point(2,4)
p2 = point(1,6)
distance = distancepoint(p1,p2)
print (f'Distance between 2 points: {distance}')
I am a Python beginner. I dont know how to fix this problem.
>Solution :
You have two options here:
- The way your code is written,
distancepointshould be a regular function (outside of a class), that takes two point objects as an input and returns a distance:
import math
class Point: # python devs usually use CamelCase for class names
def __init__(self, x, y): # x and y, because we have two coordinates, not two points
self.x = x
self.y = y
def distancepoint(p1, p2):
x1, y1 = p1.x, p1.y
x2, y2 = p2.x, p2.y
distance = math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
return distance
p1 = Point(2, 4)
p2 = Point(1, 6)
distance = distancepoint(p1, p2)
print(f"Distance between 2 points: {distance}")
- Another way to go about it, which you seemed to be aiming at, is to define
distancepointas a method of thePointclass. That means you can measure the distance
from a givenPointobject to anotherPoint.
class Point: # python devs usually use CamelCase for class names
def __init__(self, x, y): # x and y, because we have two coordinates, not two points
self.x = x
self.y = y
def distance(self, other_p):
x1, y1 = self.x, self.y
x2, y2 = other_p.x, other_p.y
distance = math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
return distance
p1 = Point(2, 4)
p2 = Point(1, 6)
distance = p1.distance(p2)
print(f"Distance between 2 points: {distance}")