Addition and multiplication puzzle

Mark Dickinson marketdickinson at yahoo.com
Sat Oct 25 11:44:46 EDT 2003


Can anyone either reproduce or explain the following
apparently inconsistent behaviours of __add__ and
__mul__?  The class Gaussian provides a sub-bare-bones
implementation of Gaussian integers (a Gaussian
integer is a complex number x+yi for which both x and
y are
integers):

class Gaussian(object):
    """class representing Gaussian integers"""

    def __init__(self, x, y = 0):
        self.real, self.imag = x, y

    def __repr__(self):
        return repr(self.real) + "+" + repr(self.imag)
+ "*i"

    def __add__(self, other):
        if type(other) != Gaussian:
            other = Gaussian(other)
        return Gaussian(self.real + other.real,
self.imag + other.imag)

    def __mul__(self, other):
        if type(other) != Gaussian:
            other = Gaussian(other)
        return Gaussian(self.real * other.real -
self.imag * other.imag, \
                          self.real * other.imag +
self.imag * other.real)

Under Python 2.3.2 I get:

>>> i = Gaussian(0, 1)
>>> i * 3
0+3*i
>>> 3 * i   # surprise!
0+3*i
>>> i + 3
3+1*i
>>> 3 + i
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: unsupported operand type(s) for +: 'int'
and 'Gaussian'

In other words, I can *multiply* an int by a Gaussian
in either order, but I can only *add* a Gaussian to an
int, not the other way around.  The surprise is that
multiplying an int by a Gaussian works---I'd expect it
to complain since there's no __rmul__ method defined,
in just the same way that 3+i produced an exception
above.  Why do addition and multiplication behave
differently?

Yours hoping for enlightenment,

Mark


__________________________________
Do you Yahoo!?
The New Yahoo! Shopping - with improved product search
http://shopping.yahoo.com





More information about the Python-list mailing list