__add__支持不同类型的加法吗? [英] __add__ to support addition of different types?
问题描述
如果python是支持重载的静态编程语言,它将非常容易解决。我正在制作一个名为Complex的类,它表示复数(我知道python有它自己的一类,但我想自己做一个),其中a是实数,b是虚数( Complex (a,b)
)。它应该支持将Complex实例加在一起( Complex(2,4)+ Complex(4,5)= Complex(6,9)
),以及添加一个整数( Complex(2,3)+ 4 =复杂(6,3)
)。但是,由于python的性质,因此...
Would be very easy to solve had python been a static programming language that supported overloading. I am making a class called Complex which is a representation of complex numbers (I know python has its own, but i want to make one myself), where a is the real number and b is the imaginary (Complex(a, b)
). It should support adding Complex instances together (Complex(2, 4) + Complex(4, 5) = Complex(6, 9)
), as well as adding an integer (Complex(2, 3) + 4 = Complex(6, 3)
). However, due to the nature of python...
__add__(self, other):
...我必须选择要支持的类,因为它无法识别编译类型时间,以及不支持功能重载。最好的解决方案是什么?我是否必须编写与 other
参数的数据类型有关的if语句?
...I have to choose which the class will support, because it won't recognize types at compile-time, as well as not supporting overloading of functions. What is the best solution? Do I have to write an if statement in relation to the datatype of the other
parameter?
推荐答案
您可以做的是检查实例Complex的内容,如果没有,则将其变成一个实例,就像这样:
What you could do is check for the thing being of instance Complex, and if not, turn it into one, like so:
def __add__(self, other):
if isinstance(other, Complex):
# do addition
else:
return self + Complex(other, 0)
这当然不会消除类型检查,但是会重用您在<$中所做的一切c $ c> __ init __ (可能正在检查输入是int还是float)。
That of course does not eliminate type checking, but it reuses whatever you are doing in __init__
(which is probably checking if input is int or float).
如果您目前不进行类型检查,在初始化中,这可能是个好主意,并且这看起来很合理,除了内置的复杂类型。
If at the moment you do not do type checking in init, it is probably a good idea, and this looks reasonable, excepting built-in complex type.
这篇关于__add__支持不同类型的加法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!