gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:32:24 25 4
gpt4 key购买 nike

这是我的 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__()

关于python - 我定义了一个 Complex 类。我该怎么做 "9+Complex",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48878949/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com