python定义一个类实现复数,并用方法实现加减乘除
时间: 2024-01-27 07:03:51 浏览: 69
设计一个复数的类
好的,下面是实现复数类的代码:
```python
class ComplexNumber:
def __init__(self, real, imag):
self.real = real
self.imag = imag
def __str__(self):
if self.imag >= 0:
return f"{self.real} + {self.imag}i"
else:
return f"{self.real} - {-self.imag}i"
def __add__(self, other):
return ComplexNumber(self.real + other.real, self.imag + other.imag)
def __sub__(self, other):
return ComplexNumber(self.real - other.real, self.imag - other.imag)
def __mul__(self, other):
real = self.real * other.real - self.imag * other.imag
imag = self.real * other.imag + self.imag * other.real
return ComplexNumber(real, imag)
def __truediv__(self, other):
denominator = other.real**2 + other.imag**2
real = (self.real * other.real + self.imag * other.imag) / denominator
imag = (self.imag * other.real - self.real * other.imag) / denominator
return ComplexNumber(real, imag)
```
上面的代码中,我们定义了一个复数类,包含了实部和虚部两个属性。同时,我们重载了`__str__`方法,使得打印对象时能够输出正常的复数形式。此外,我们还重载了加减乘除四个运算符,实现了复数的加减乘除。
阅读全文