使用类的封装性思想:声明复数类Complex,成员变量包括实部和虚部,成员方法包括实现由字符串构造复数,复数加法,减法,字符串描述,比较相等的操作
时间: 2024-06-03 07:09:47 浏览: 17
class Complex:
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def __str__(self):
if self.imaginary >= 0:
return f"{self.real} + {self.imaginary}i"
else:
return f"{self.real} - {-self.imaginary}i"
def __eq__(self, other):
return self.real == other.real and self.imaginary == other.imaginary
def __add__(self, other):
return Complex(self.real + other.real, self.imaginary + other.imaginary)
def __sub__(self, other):
return Complex(self.real - other.real, self.imaginary - other.imaginary)
@classmethod
def from_string(cls, string):
real, imaginary = string.split("+")
real = float(real.strip())
imaginary = float(imaginary.strip()[:-1])
return cls(real, imaginary)
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)