【发布时间】:2022-08-14 07:34:32
【问题描述】:
我有一个任务问题。根据问题的情况,给出两个坐标为 xyz 的点 p1、p2,你需要使用类在 3D 空间中求出这些点之间的距离。任务本身似乎很简单,但对我来说,困难在于距离的计算必须使用只有一个距离(其他)参数的方法进行,我不明白如何做到这一点,如果需要两个变量,它们将给出两个点的坐标,在方法中我们只能使用一个。
我试图这样做,但我收到一个错误(不支持的操作数类型 -:\'str\' 和 \'str\'):
from math import sqrt
class Point3D:
x: float
y: float
z: float
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
@staticmethod
def distance(other):
return sqrt((other[0][0] - other[1][0]) ** 2 + (other[0][1] - other[1][1]) ** 2 + (other[0][2] - other[1][2]) ** 2)
p1 = [1, 2, 3]
p2 = [3, 2, 1]
s1 = Point3D(*p1)
s2 = Point3D(*p2)
print(Point3D.distance((s1, s2)))
>>>unsupported operand type(s) for -: \'str\' and \'str\'
我也尝试这样做,但它给出了一个错误(\'str\'对象没有属性\'x\')
# The rest of the code is the same
@staticmethod
def distance(other):
return sqrt((other[0].x - other[1].x) ** 2 + (other[0].y - other[1].y) ** 2 + (other[0].z - other[1].z) ** 2)
p1 = [1, 2, 3]
p2 = [3, 2, 1]
s1 = Point3D(*p1)
s2 = Point3D(*p2)
print(Point3D.distance((s1, s2)))
>>>AttributeError: \'str\' object has no attribute \'x\'
还有可以正常工作但不被接受的代码,因为距离需要 2 个参数,但需要 1 个(这是他们不接受我的代码的示例):
# The rest of the code is the same
def distance(self, other):
return sqrt((other.x1 - self.x1) ** 2 + (other.y1 - self.y1) ** 2 + (other.z1 - self.z1) ** 2)
p1 = [1, 2, 3]
p2 = [3, 2, 1]
point1 = Point3D(*p1)
point2 = Point3D(*p2)
print(point1.distance(point2))
>>>2.8284271247461903
请帮我修复代码,以便它与 distance(other) 方法一起使用并且不会引发错误。如果需要,您可以删除 @staticmethod。老实说,我不知道该怎么办了。我会很高兴得到任何帮助
-
你好丹尼尔,欢迎来到 StackOverflow!似乎最后一段代码是正确的,并且只接受你演示的一个参数。
self参数不需要传入,它指的是方法的“所有者”(在本例中为point1)。 -
还有,你是当然在第一个和第二个 sn-ps 中的代码是你写的吗?因为我在代码中的任何地方都看不到
str或任何字符串。当我运行 sn-p 1 时,我得到了错误TypeError: \'Point3D\' object is not subscriptable,这更有意义。
标签: python coordinates