声明复数类Complex,成员变量包括实部和虚部,成员方法包括实现由字符串构造复数,复数加法,减法,字符串描述,比较相等的操作
时间: 2024-05-21 09:13:06 浏览: 101
class Complex:
def __init__(self, real=0, imag=0):
self.real = real
self.imag = imag
def __str__(self):
if self.imag < 0:
return f"{self.real} - {-self.imag}i"
else:
return f"{self.real} + {self.imag}i"
def __eq__(self, other):
if isinstance(other, Complex):
return self.real == other.real and self.imag == other.imag
else:
return False
def __add__(self, other):
if isinstance(other, Complex):
return Complex(self.real + other.real, self.imag + other.imag)
else:
raise TypeError("unsupported operand type(s) for +: 'Complex' and '{type(other).__name__}'")
def __sub__(self, other):
if isinstance(other, Complex):
return Complex(self.real - other.real, self.imag - other.imag)
else:
raise TypeError("unsupported operand type(s) for -: 'Complex' and '{type(other).__name__}'")
@classmethod
def from_string(cls, s):
s = s.strip()
if s.endswith("i"):
s = s[:-1]
if s.endswith("+") or s.endswith("-"):
s += "1"
return cls(0, int(s))
else:
real, imag = map(int, s.split("+"))
return cls(real, imag)
阅读全文