Python面向对象求两点欧氏距离的point_distance方法编写求助
你需要先在代码文件开头引入math模块用于平方根计算:import math
接下来给你两种符合需求的point_distance方法实现:
方案1:完全贴合你的伪代码逻辑
接收__sub__方法的返回结果作为入参,直接计算距离:
def point_distance(self, sub_result): # sub_result为__sub__返回的Point实例,存储了x坐标差的平方、y坐标差的平方 square_sum = sub_result.x() + sub_result.y() return math.sqrt(square_sum)
调用示例:
p1 = Point(1, 2) p2 = Point(4, 6) sub_res = p1 - p2 print(p1.point_distance(sub_res)) # 输出结果为5.0
方案2:更易用的优化实现
无需手动提前执行减法操作,直接传入另一个点实例即可计算距离,调用更简洁:
def point_distance(self, other_point): sub_res = self - other_point square_sum = sub_res.x() + sub_res.y() return math.sqrt(square_sum)
调用示例:
p1 = Point(1, 2) p2 = Point(4, 6) print(p1.point_distance(p2)) # 直接输出结果为5.0
内容的提问来源于stack exchange,提问作者Renaissance Man
相关产品推荐
相关产品推荐

