我定义了一个Complex类。我怎么能这样做" 9 + Complex"

时间:2018-02-20 06:12:41

标签: python operator-overloading

这是我的复杂课程,我超载了#34; +"

class Complex(object):
    def __init__(self, real, imag):
        self.__imag = float(imag)
        self.__real = float(real)
        self.__attr = {
            'imag': self.__imag,
            'real': self.__real
        }

    def __add__(self, other):
        if isinstance(other, Complex):
            self.__imag += float(other.imag)
            self.__real += float(other.real)
        elif isinstance(other, int) or isinstance(other, float):
            self.__real += other
        else:
            print 'expect int or Complex, not {}'.format(type(other))
            raise TypeError
        return self

    def __getattr__(self, item):
        try:
            return self.__attr[item]
        except TypeError as e:
            print e
            print 'no attribute{}'.format(item)

现在,如果我加上" Complex + int"它已经满了,但是当我加上" int + Complex"时,我得到了这个错误

TypeError: unsupported operand type(s) for +: 'int' and 'Complex'

1 个答案:

答案 0 :(得分:2)

将此添加到您的班级:

def __radd__(self, other):
    return Complex.__add__(self,other)

请参阅此LINK了解更多信息,例如__iadd__()