我正在尝试为Complex类编写代码,但我一直在为此代码获取一个例外:+的不支持的操作数类型:' float'和'复杂'
def __add__(a, other):
if isinstance(a, (float,int)):
a = Complex(a, 0)
if isinstance(other, (float,int)):
other = Complex(other, 0)
return Complex(a.real+other.real, a.imag+other.imag)
它应该按预期工作,但该方法无法容纳real + Complex。有什么想法为什么这个代码可能无法正常工作?
Output: Testing num + x
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-77-f3b14d8552ce> in <module>()
1 # test your implementation of Complex
----> 2 test_complex(Complex)
C:\Users\User\Desktop\beaver\Python_5_HW\graders\grader36.pyc in test_complex(StdntClass)
C:\Users\User\Desktop\beaver\Python_5_HW\graders\grader36.pyc in test_attr(StdntClass)
unsupported operand type(s) for +: 'float' and 'Complex'