设计一个复数类,实现相应的加减乘方法,注意方法设计中的参数和返回值的使用。
时间: 2024-02-06 09:11:57 浏览: 17
好的,我可以帮你设计一个复数类,实现相应的加减乘方法。以下是一个基本的复数类的代码示例:
```python
class ComplexNumber:
def __init__(self, real_part, imag_part):
self.real_part = real_part
self.imag_part = imag_part
def __add__(self, other):
return ComplexNumber(self.real_part + other.real_part, self.imag_part + other.imag_part)
def __sub__(self, other):
return ComplexNumber(self.real_part - other.real_part, self.imag_part - other.imag_part)
def __mul__(self, other):
return ComplexNumber(self.real_part * other.real_part - self.imag_part * other.imag_part,
self.real_part * other.imag_part + self.imag_part * other.real_part)
def __str__(self):
return '{}{}{}i'.format(self.real_part, '+' if self.imag_part >= 0 else '-', abs(self.imag_part))
# Test code
if __name__ == '__main__':
c1 = ComplexNumber(1, 2)
c2 = ComplexNumber(3, -4)
print(c1 + c2) # Output: 4-2i
print(c1 - c2) # Output: -2+6i
print(c1 * c2) # Output: 11+2i
```
在上面的代码中,`__init__` 方法用于初始化复数对象,`__add__`、`__sub__` 和 `__mul__` 方法分别实现了两个复数对象的加、减和乘法运算,`__str__` 方法用于将复数对象转换为字符串输出。在 `__add__`、`__sub__` 和 `__mul__` 方法中,我们使用了符号重载技术,使得我们可以通过 `+`、`-` 和 `*` 运算符来对复数对象进行加、减和乘法运算。以上代码是一个基本的复数类的实现,你可以根据自己的需要进行修改和扩展。