用python设计一个类,实现向量的加、减、内积等操作
时间: 2023-07-14 19:12:30 浏览: 51
可以设计一个名为Vector的类来实现向量的加、减、内积等操作,如下所示:
```python
class Vector:
def __init__(self, *args):
self.values = list(args)
def __repr__(self):
return f"Vector({', '.join(str(i) for i in self.values)})"
def __add__(self, other):
if len(self.values) != len(other.values):
raise ValueError("Vectors must have the same length.")
new_values = [self.values[i] + other.values[i] for i in range(len(self.values))]
return Vector(*new_values)
def __sub__(self, other):
if len(self.values) != len(other.values):
raise ValueError("Vectors must have the same length.")
new_values = [self.values[i] - other.values[i] for i in range(len(self.values))]
return Vector(*new_values)
def __mul__(self, other):
if isinstance(other, Vector):
if len(self.values) != len(other.values):
raise ValueError("Vectors must have the same length.")
return sum([self.values[i] * other.values[i] for i in range(len(self.values))])
elif isinstance(other, (int, float)):
return Vector(*[other * i for i in self.values])
else:
raise TypeError("Unsupported operand type(s) for *: 'Vector' and '{}'".format(type(other).__name__))
```
使用示例:
```python
a = Vector(1, 2, 3)
b = Vector(4, 5, 6)
c = a + b
d = a - b
e = a * b
f = a * 2
print(c) # Vector(5, 7, 9)
print(d) # Vector(-3, -3, -3)
print(e) # 32
print(f) # Vector(2, 4, 6)
```
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)