簡體   English   中英

計算A點類Python中兩點之間的距離

[英]Calculating the distance between two points in A Point Class Python

我正在努力理解 python 中面向對象編程的想法。 我目前正在嘗試使用 Point 類計算兩點之間的歐幾里得距離

import math

class Point(object):
    """A 2D point in the cartesian plane"""

    def __init__(self, x, y):
        self._x = x
        self._y = y

    def __repr__(self):
        return 'Point({}, {})'.format(self._x, self._y)

    def dist_to_point(self, Point):
        dist = math.sqrt((self._x - Point.x())**2 + (self._y - Point.y())**2)
        return dist

我知道 dist_to_point 方法是錯誤的,因為 python 正在返回:

測試結果:'Point' 對象沒有屬性 'x'

我很難理解引用是如何工作的? 我在 Point 對象中定義了 Point,為什么我不能使用它?

.self 又是怎么回事? 如果我想在Point類下使用一個點的x和y坐標,我必須調用self._x和self._y?

import math

class Point(object):
    """A 2D point in the cartesian plane"""

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return 'Point({}, {})'.format(self.x, self.y)

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

p1 = Point(4,9)
p2 = Point(10,5)
print(p1.dist_to_point(p2))

>> 7.211102550927978

self 是對象實例
變量前的“_”表示按照慣例它是私有的(因此在此處不適用)
x & y 后沒有“()”

您已聲明 self._x 以便您可以使用它,但您尚未聲明第二點。 先聲明一下。 最好在__init__()中再添加兩個參數,並將第一個參數編輯為 x1 y1 並添加參數 x2 y2。 然后將它們初始化為self.x1=x1 self.y1=y1 self.x2=x2 self.y2=y2 然后將dist_to_point()方法更改為:

def dist_to_point(self):
      return math.sqrt((self.x1-self.x2)**2+(self.y1-self.y2)**2)

在 Python 中,在類方法或變量之前使用下划線是一種約定,表明它是私有的,不應在類之外使用。 您的問題的解決方案可能是使 Point 類的 x 和 y 公共變量,這樣您就可以在類外訪問它們。 下面是一個例子:

import math


class Point:
    """A 2D point in the cartesian plane"""

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return 'Point({}, {})'.format(self._x, self._y)

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


p1 = Point(0, 0)
p2 = Point(1, 1)

distance = p1.dist_to_point(p2)

print(distance)

公開這些值可能並不總是最好的解決方案,但對於這個簡單的情況,沒關系

而且您還在類變量訪問之后放置了 () :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM