gpt4 book ai didi

Python类--需要解释

转载 作者:太空宇宙 更新时间:2023-11-03 13:03:40 24 4
gpt4 key购买 nike

我有一个关于类定义及其用途的一般性问题。其中一本书中的以下代码工作正常,但我有一个一般性问题。

这里我们定义了一个类 Point 并创建了 2 个实例 Point1 和 Point2。在计算point2的距离时,如何传递point1对象?

point1 不是点对象,而 other_point 被表示为变量。

我有点困惑。

代码:

import math
class Point:
def move(self, x, y):
self.x = x
self.y = y
def reset(self):
self.move(0, 0)
def calculate_distance(self, other_point):
print("Inside calculating distance")

return math.sqrt(
(self.x - other_point.x)**2 +
(self.y - other_point.y)**2)

point1 = Point()
point2 = Point()
point1.reset()
point2.move(5,0)
print(point2.calculate_distance(point1))

最佳答案

当您创建一个 Point 对象时,会发生几件事。

point1 = Point()
point2 = Point()

发生的事情之一是属于 Point 类的任何方法都被绑定(bind)。这意味着该方法中的参数之一是固定的,因此它始终引用创建的实例。让我们看一下 calculate_distance 的定义。

def calculate_distance(self, other_point):
print("Inside calculating distance")

return math.sqrt(
(self.x - other_point.x)**2 +
(self.y - other_point.y)**2)

您大概可以猜到哪个参数是固定的。当调用 Point() 并创建实例时,calculate_distnaceself 参数是固定的,因此它始终引用该实例。所以无论何时你这样做:

point1.calculate_distance(x)

你正在做与此相同的事情:

Point.calculate_distance(point1, x)

每当你这样做时:

point2.calculate_distance(point1)

你正在做与此相同的事情:

Point.calculate_distance(point2, point1)

关于Python类--需要解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11092510/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com