Skip to main content
 首页 » 编程设计

python之我定义了一个 Complex 类。我该怎么做 "9+Complex"

2024年09月07日1352php

这是我的 Complex 类,我重载了“+”

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' 

请您参考如下方法:

将此添加到您的类(class):

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

引用这个LINK了解更多信息,例如 __iadd__()。