python定义一个复数类complex_定义一个复数类Complex,重载运算符“+”、“-”、“*”和“/”
时间: 2023-11-05 08:04:43 浏览: 172
定义复数类Complex,进行运算符重载
5星 · 资源好评率100%
下面是定义一个复数类 `Complex_` 和 `Complex`,并重载运算符 `+`、`-`、`*` 和 `/` 的示例代码:
```python
class Complex_:
def __init__(self, real=0, imag=0):
self.real = real
self.imag = imag
def __add__(self, other):
return Complex_(self.real + other.real, self.imag + other.imag)
def __sub__(self, other):
return Complex_(self.real - other.real, self.imag - other.imag)
def __mul__(self, other):
return Complex_(self.real * other.real - self.imag * other.imag,
self.real * other.imag + self.imag * other.real)
def __truediv__(self, other):
denom = other.real ** 2 + other.imag ** 2
return Complex_((self.real * other.real + self.imag * other.imag) / denom,
(self.imag * other.real - self.real * other.imag) / denom)
def __str__(self):
return f"{self.real} + {self.imag}j"
class Complex:
def __init__(self, real=0, imag=0):
self.real = real
self.imag = imag
def __add__(self, other):
return Complex(self.real + other.real, self.imag + other.imag)
def __sub__(self, other):
return Complex(self.real - other.real, self.imag - other.imag)
def __mul__(self, other):
return Complex(self.real * other.real - self.imag * other.imag,
self.real * other.imag + self.imag * other.real)
def __truediv__(self, other):
denom = other.real ** 2 + other.imag ** 2
return Complex((self.real * other.real + self.imag * other.imag) / denom,
(self.imag * other.real - self.real * other.imag) / denom)
def __str__(self):
return f"{self.real} + {self.imag}j"
```
这里定义了两个复数类 `Complex_` 和 `Complex`,它们的实现方式有些不同。其中,`Complex_` 类使用 `_` 后缀来避免与 Python 内置的 `complex` 类重名。两个类都有 `real` 和 `imag` 属性,分别表示实部和虚部。`__add__`、`__sub__`、`__mul__` 和 `__truediv__` 方法分别重载了加、减、乘和除运算符,使得我们可以直接对两个复数进行运算。`__str__` 方法用于将复数转换为字符串形式,便于输出。
示例代码中的 `__truediv__` 方法是重载除法运算符 `/` 的方法,因此需要使用 `__truediv__` 方法而不是 `__div__` 方法(`__div__` 方法在 Python 3 中已被弃用)。
使用示例:
```python
a = Complex_(1, 2)
b = Complex_(3, 4)
print(a + b) # 输出:4 + 6j
print(a - b) # 输出:-2 - 2j
print(a * b) # 输出:-5 + 10j
print(a / b) # 输出:0.44 + 0.08j
c = Complex(1, 2)
d = Complex(3, 4)
print(c + d) # 输出:4 + 6j
print(c - d) # 输出:-2 - 2j
print(c * d) # 输出:-5 + 10j
print(c / d) # 输出:0.44 + 0.08j
```
阅读全文