return type question - operator oveloading
Chris Liechti
cliechti at gmx.net
Sat Mar 16 21:59:44 EST 2002
arthur.siegel at rsmi.com wrote in
news:mailman.1016322689.22392.python-list at python.org:
> Given:
>
> class Complex(complex):
> def __mul__(self,other):
> other=Complex(other)
> t = complex.__mul__(self,other)
> return Complex(t.real,t.imag)
> __rmul__ = __mul__
>
> def __add__(self,other):
> other=Complex(other)
> return
> Complex(self.real.__add__(other.real),
> self.imag.__add__(other.imag))
> __radd__ = __add__
>
> Then:
>
> print type(Complex(5,4) * 7)
>>><class '__main__.Complex'>
> print type(7 * Complex(5,4))
>>><class '__main__.Complex'>
> print type(Complex(5,4) + 7)
>>><class '__main__.Complex'>
>
> But:
>
> print type(7 + Complex(5,4))
>>><type 'complex'>
yes i get the same results (py 2.2).
> Multiple choice:
> That the result at But is a surprise to me because I am missing:
> 1)Something obvious about __radd__ or general classic syntax
> 2)Something related to new style classes
> 3)Other
i vote for "3) Other". i think the integer class defines __add__ for
complex numbers but not __mul__ for complex numbers. thus when adding
"7+Complex(5,4)" your __radd__ is never called cause the int class
indles it.
chris
--
Chris <cliechti at gmx.net>
More information about the Python-list
mailing list