我是python類的新手。我遇到了一個錯誤,所以我想計算兩個坐標之間的距離。但是我正在努力從 p1 和 p2 或 p2 和 p3 中獲取值 x 和 y 值,...并在計算兩個給定坐標之間的距離的方法中使用這些值。
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))
提前感謝<3
uj5u.com熱心網友回復:
您必須將第二點作為引數傳遞給該distance方法。然后就可以訪問 和 兩個點的和x屬性y了。selfother
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
(您可以讓和other的默認值,然后只回傳 0。不過,我不確定是否非常需要計算一個點與它自身之間的微不足道的距離。)Noneother is None
順便說一句,您可以使用內置complex型別來操作二維點。
def distance(self, other):
p1 = complex(self.x, self.y)
p2 = complex(other.x, other.y)
return abs(p1 - p2)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/521500.html
標籤:Python班级方法
