python自定义复数类,重载运算符加、减、乘或除。本实例要求编写代码,重载运算符,使列表支持四则运算。代码及注释
时间: 2024-05-07 10:19:06 浏览: 67
下面是一个Python自定义复数类的例子,其中重载了加、减、乘、除四种运算符以支持复数的计算:
```python
class Complex:
def __init__(self, real, imag):
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):
denominator = other.real**2 + other.imag**2
return Complex((self.real*other.real + self.imag*other.imag)/denominator,
(self.imag*other.real - self.real*other.imag)/denominator)
def __str__(self):
return '{} + {}i'.format(self.real, self.imag)
```
其中,`__add__`、`__sub__`、`__mul__`和`__truediv__`分别对应加、减、乘、除四种运算符,将两个复数进行相应的计算并返回结果。`__str__`方法用于将复数以字符串形式输出。
如果要创建一个复数对象,可以使用类似下面的代码:
```python
c1 = Complex(1, 2)
c2 = Complex(3, 4)
```
然后可以对这两个复数对象进行加、减、乘、除等操作,例如:
```python
print(c1 + c2) # 输出:4 + 6i
print(c1 - c2) # 输出:-2 - 2i
print(c1 * c2) # 输出:-5 + 10i
print(c1 / c2) # 输出:0.44 + 0.08i
```
阅读全文