我正在努力理解 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?
uj5u.com熱心網友回復:
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 之后沒有“()”
uj5u.com熱心網友回復:
您已宣告 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)
uj5u.com熱心網友回復:
在 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)
公開這些值可能并不總是最好的解決方案,但對于這個簡單的情況,沒關系
而且您還在類變數訪問之后放置了 () :)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/315781.html
上一篇:從PowerShell創建azure虛擬網路對等互連
下一篇:ReactNative渲染物件鍵
