Python实现3D空间两点距离:单参数distance方法问题求助
3D空间两点距离:单参数
distance方法实现 问题
需要实现一个Point3D类,计算3D空间中两点的距离,要求distance方法只能有一个参数(other)。
错误分析
- 第一种代码错误:用静态方法接收点元组后,试图用列表索引(
other[0][0])访问Point3D对象的坐标,但对象的坐标是通过属性x/y/z访问的,而非列表索引;错误提示中的字符串运算问题,大概率是初始化时误传入了字符串类型的坐标值。 - 第二种代码错误:同样使用静态方法,但可能因代码缩进错误导致方法未绑定到类,或者传入的参数不是
Point3D实例,导致无法访问x属性。 - 第三种代码能运行,但你认为它有两个参数(
self和other)不符合要求,实际上self是Python实例方法的隐式参数,若任务允许这种情况,它是更合理的实现。
解决方案
方案1:静态方法(严格单参数)
将两个Point3D实例打包为元组作为唯一参数传入静态方法:
from math import sqrt class Point3D: def __init__(self, x: float, y: float, z: float): self.x = x self.y = y self.z = z @staticmethod def distance(other): # 解构元组得到两个点实例 p1, p2 = other return sqrt((p1.x - p2.x)**2 + (p1.y - p2.y)**2 + (p1.z - p2.z)**2) # 测试 p1_coords = [1, 2, 3] p2_coords = [3, 2, 1] s1 = Point3D(*p1_coords) s2 = Point3D(*p2_coords) print(Point3D.distance((s1, s2))) # 输出:2.8284271247461903
方案2:实例方法(符合OOP逻辑)
如果任务中“单参数”指的是除self外仅一个显式参数,那么这种实例方法是标准实现,self代表当前点,other代表另一个点:
from math import sqrt class Point3D: def __init__(self, x: float, y: float, z: float): self.x = x self.y = y self.z = z def distance(self, other): return sqrt((self.x - other.x)**2 + (self.y - other.y)**2 + (self.z - other.z)**2) # 测试 point1 = Point3D(1, 2, 3) point2 = Point3D(3, 2, 1) print(point1.distance(point2)) # 输出:2.8284271247461903
关键说明
- 方案1严格满足“仅一个参数”的要求,适合任务明确禁止
self作为参数的场景。 - 方案2是Python面向对象的常规写法,
self是实例方法的隐式参数,大多数情况下任务中的“单参数”指的是显式定义的参数,这种写法更易维护。
内容的提问来源于stack exchange,提问作者Daniil Demchenko
相关产品推荐
相关产品推荐

