输出不对,<__main__.Vector object at 0x0000021835238790> <__main__.Vector object at 0x0000021835238790> <__main__.Vector object at 0x0000021835238790> <__main__.Vector object at 0x0000021835238790>
时间: 2023-12-09 09:05:36 浏览: 77
非常抱歉,我犯了一个错误。以下是修正后的代码:
```python
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y, self.z + other.z)
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y, self.z - other.z)
def __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar, self.z * scalar)
def __truediv__(self, scalar):
return Vector(self.x / scalar, self.y / scalar, self.z / scalar)
def __repr__(self):
return f"Vector({self.x}, {self.y}, {self.z})"
@property
def length(self):
return (self.x ** 2 + self.y ** 2 + self.z ** 2) ** 0.5
```
我添加了一个`__repr__`方法,用于在打印向量时返回可读性更好的字符串形式。请再次尝试使用:
```python
a = Vector(1, 2, 3)
b = Vector(4, 5, 6)
print(a + b) # 输出 Vector(5, 7, 9)
print(a - b) # 输出 Vector(-3, -3, -3)
print(a * 10) # 输出 Vector(10, 20, 30)
print(a / 2) # 输出 Vector(0.5, 1.0, 1.5)
print(a.length) # 输出 3.7416573867739413
```
这次应该能够正确输出结果了。
阅读全文