对复数1+2i 、3+4i、 6-7i 等对象进行抽象,声明复数类,并分析其属性和行为。
时间: 2024-09-18 20:11:52 浏览: 33
复数_visualc++_复数入门_roottt2_
复数类(ComplexNumber)是对数学上复数的一种抽象,它通常包括实部(real part)和虚部(imaginary part)这两个基本属性。我们可以定义如下:
```python
class ComplexNumber:
def __init__(self, real=0, imag=0):
self.real = real
self.imag = imag
# 属性访问方法
@property
def real(self):
return self._real
@real.setter
def real(self, value):
if not isinstance(value, (int, float)):
raise ValueError("实部必须是数字")
self._real = value
@property
def imag(self):
return self._imag
@imag.setter
def imag(self, value):
if not isinstance(value, (int, float)):
raise ValueError("虚部必须是数字")
self._imag = value
# 行为方法:加法、减法、乘法、除法
def add(self, other):
real_sum = self.real + other.real
imag_sum = self.imag + other.imag
return ComplexNumber(real_sum, imag_sum)
def subtract(self, other):
real_diff = self.real - other.real
imag_diff = self.imag - other.imag
return ComplexNumber(real_diff, imag_diff)
def multiply(self, other):
real_prod = self.real * other.real - self.imag * other.imag
imag_prod = self.real * other.imag + self.imag * other.real
return ComplexNumber(real_prod, imag_prod)
def divide(self, other):
if other.real == 0 and other.imag == 0:
raise ZeroDivisionError("除数不能为零")
denominator = other.real ** 2 + other.imag ** 2
real_quotient = (self.real * other.real + self.imag * other.imag) / denominator
imag_quotient = (self.imag * other.real - self.real * other.imag) / denominator
return ComplexNumber(real_quotient, imag_quotient)
# 重写字符串方法,以便于输出
def __str__(self):
return f"{self.real} + {self.imag}i"
```
这个类包含了复数的基本属性(实部和虚部),以及常见的复数运算方法如加、减、乘、除。同时,为了方便用户查看复数,还实现了`__str__`方法,使得可以直接打印出复数的形式。
阅读全文