我正在努力理解python中面向对象编程的思想。我目前正在尝试使用Point类
计算2点之间的欧几里得距离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'
我正在努力理解引用是如何工作的?我定义点作为一个点对象,为什么我不能使用这个?
还有。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是对象实例
"_">
no "()"在x &y
您已经声明了self。所以你可以使用它,但是你还没有声明第二点。首先声明它。最好在__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中,在类方法或变量之前使用下划线是一种惯例,表示它是私有的,不应该在类外使用。您的问题的解决方案可能是使x和y的Point类的公共变量,这样您就可以访问他们的类之外。下面是一个例子:
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)
公开这些值可能并不总是最好的解决方案,但是对于这个简单的例子中很好
你还把()放在类变量访问之后:)