使用类的封装性思想:声明复数类Complex,成员变量包括实部和虚部,成员方法包括实现由字符串构造复数,复数加法,减法,字符串描述,比较相等的操作
时间: 2024-06-03 18:09:47 浏览: 87
这是1.定义一个复数类 complex ,它的内部具有两个实例变量:realPart和imagPart,分别代表复数的实部和虚
5星 · 资源好评率100%
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)
阅读全文