设计一个三维向量类,并实现向量的加法、减法以及向量与标量的乘法和除法运算(要求重载__add__、sub、__mul__等方法)并进行实验
时间: 2023-06-02 22:04:17 浏览: 182
好的,我明白了。以下是我对你的第一个问题的回答:
首先,我会先实现一个三维向量类。这个类应该包含三个属性:x、y 和 z,分别表示向量在三个维度上的分量。
接下来,我会实现向量的加法、减法以及向量与标量的乘法和除法运算。具体来说,我会重载 __add__、__sub__、__mul__ 和 __truediv__ 这四个方法。这些方法的实现方式如下:
__add__(self, other):
return Vector3D(self.x + other.x, self.y + other.y, self.z + other.z)
__sub__(self, other):
return Vector3D(self.x - other.x, self.y - other.y, self.z - other.z)
__mul__(self, scalar):
return Vector3D(self.x * scalar, self.y * scalar, self.z * scalar)
__truediv__(self, scalar):
return Vector3D(self.x / scalar, self.y / scalar, self.z / scalar)
最后,我会进行实验,测试各种运算是否正确。
代码实现如下:
class Vector3D:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __add__(self, other):
return Vector3D(self.x + other.x, self.y + other.y, self.z + other.z)
def __sub__(self, other):
return Vector3D(self.x - other.x, self.y - other.y, self.z - other.z)
def __mul__(self, scalar):
return Vector3D(self.x * scalar, self.y * scalar, self.z * scalar)
def __truediv__(self, scalar):
return Vector3D(self.x / scalar, self.y / scalar, self.z / scalar)
def __str__(self):
return "<{},{},{}>".format(self.x, self.y, self.z)
# 测试:
v1 = Vector3D(1, 2, 3)
v2 = Vector3D(4, 5, 6)
print("v1 + v2 =", v1 + v2) # <5,7,9>
print("v1 - v2 =", v1 - v2) # <-3,-3,-3>
print("v1 * 2 =", v1 * 2) # <2,4,6>
print("v2 / 2 =", v2 / 2) # <2.0,2.5,3.0>
阅读全文
相关推荐












