[Tutor] Operator overloading surprise
Arthur Siegel
ajs@ix.netcom.com
Sun, 17 Mar 2002 09:38:14 -0500
I posted the below on the python-list, and other than
a response seeming to share my surprise (and verifying that
the behavior can be duplicated), not much interest. Thought
I'd try here.
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'>
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
Art