【发布时间】:2019-08-08 11:20:56
【问题描述】:
我正在学习这门 Python Edx 课程,下面是介绍 OOP 时给出的示例之一。这是一个基本问题,你们很多人会否决它,但在我继续之前我需要了解这一点。
我已经在 Reddit 上搜索过,也在 Edx 论坛上问过这个问题,但还是不明白。我也在这个网站上搜索过这个特定的编码示例。
Reddit:https://www.reddit.com/r/learnpython/comments/a54y04/explanation_needed_on_a_simple_class_creation/
class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, other):
x_diff_sq = (self.x-other.x)**2
y_diff_sq = (self.y-other.y)**2
return (x_diff_sq + y_diff_sq)**0.5
point1 = Coordinate(1,2)
point2 = Coordinate(3,4)
print(point1.distance(point2))
我想了解的是程序如何确定“other.x”值?因为我无处为 other.x 和 other.y 赋值。
对于 self.x 和 self.y,有一个明确的赋值发生,但对于“other.x”和“other.y”没有这样的赋值。程序如何将“3”分配给“other.x”,将“4”分配给“other.y”?
【问题讨论】:
-
程序创建
point1和point2,然后调用point1.distance(point2)。在这种情况下,point2是为方法distance的参数other传递的参数,并且分别为.x和.y包含 3 和 4。