+:' float'不支持的操作数类型和'复杂'

时间:2017-07-04 00:31:47

标签: python complex-numbers operations isinstance

我正在尝试为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'

0 个答案:

没有答案