此程序是封装复数类,要求补全代码,请有会的人帮忙看一下该如何补全这个代码。谢谢。
class MyComplex(object):
def __init__(self, x=0, y=0):
self._a = x
self._b = y
def __add__(self, other):
other = list(str(other))
if 'i' not in other:
a = eval(other)
b = 0
else:
length = len(other)
index = []
for i in range(length):
if other[i] in '+-':
index.append(i)
if index[0] == 0:
a = eval(''.join(other[index[0]:index[1]]))
b = eval(''.join(other[index[1]:-1]))
else:
a = eval(''.join(other[:index[0]]))
b = eval(''.join(other[index[0]:-1]))
return MyComplex(x=self._a + a, y=self._b + b)
def __sub__(self, other):
other = list(str(other))
if 'i' not in other:
a = eval(other)
b = 0
else:
length = len(other)
index = []
for i in range(length):
if other[i] in '+-':
index.append(i)
if index[0] == 0:
a = eval(''.join(other[index[0]:index[1]]))
b = eval(''.join(other[index[1]:-1]))
else:
a = eval(''.join(other[:index[0]]))
b = eval(''.join(other[index[0]:-1]))
return MyComplex(x=self._a - a, y=self._b - b)
def __doubleOrInt__(self, num):
if type(num) == int:
return str(num)
else:
return "{.2f}".format(num)
def __isOne(self, num):
if num == "1":
return ""
elif num == "-1":
return '-'
else:
return num
def __str__(self):
if self._b > 0:
return f"{self._a}+{self._b}i"
elif self._b == 0:
return f"{self._a}"
else:
return f"{self._a}{self._b}i"
if __name__ == '__main__':
one = MyComplex(1, 3)
two = MyComplex(-2, 4)
three = one.__add__(two)
print("one=", one)
print('two=', two)
print('three=', three)
class MyComplex(object):
def __init__(self,x=0,y=0):
self.__a = x
self.__b = y
def __add__(self, other):
x = self.__a + other.__a
y = self.__b + other.__b
return MyComplex(x, y)
def __sub__(self, other):
x = self.__a - other.__a
y = self.__b - other.__b
return MyComplex(x, y)
def __str__(self):
if self.__a==0:
if self.__b==0:
return '0'
return f'{self.__b}i'
if self.__b==0:
return str(self.__a)
sign = '+' if self.__b>0 else ''
return f'{self.__a}{sign}{self.__isOne(self.__doubleOrInt(self.__b))}i'
def __doubleOrInt(self, num):
if type(num) == int:
return str(num)
else:
return str(round(num,2))
def __isOne(self, num):
if num=='1':
return ''
elif num=='-1':
return '-'
else:
return num
def __repr__(self):
return self.__str__()
if __name__ == '__main__':
num1 = MyComplex( 5, 7)
num2 = MyComplex( -5, -1)
num3 = MyComplex( -3, -7)
print("num1 = " + str(num1))
print("num2 = " + str(num2))
print("num3 = " + str(num3))
num4 = num1 + num2
num5 = num2 - num3
print("num1+num2 = " + str(num4))
print("num2-num3 = " + str(num5))
''' out:
num1 = 5+7i
num2 = -5-5i
num3 = -3-7i
num1+num2 = 2i
num2-num3 = -2+2i
'''