繁体   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