python定义一个复数类
时间: 2023-09-27 11:08:34 浏览: 80
以下是一个简单的Python复数类的定义:
```python
class ComplexNumber:
def __init__(self, real, imag):
self.real = real
self.imag = imag
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):
return ComplexNumber(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 ComplexNumber((self.real * other.real + self.imag * other.imag)/denominator, (self.imag * other.real - self.real * other.imag)/denominator)
def __str__(self):
if self.imag >= 0:
return f"{self.real} + {self.imag}i"
else:
return f"{self.real} - {-self.imag}i"
# 测试
a = ComplexNumber(3, 4)
b = ComplexNumber(2, -1)
print(a + b) # 输出:5 + 3i
print(a - b) # 输出:1 + 5i
print(a * b) # 输出:(10 + 5i)
print(a / b) # 输出:(0.4 + 1.8i)
```
以上的代码中,我们定义了一个名为ComplexNumber的类,它有两个属性:实部和虚部。我们还重载了加、减、乘、除和字符串表示方法,以便我们可以像使用内置类型一样使用这个自定义类型。
阅读全文