[Tutor] Defining operators for custom types

Mark Young marky1991 at gmail.com
Sat Feb 13 00:41:09 CET 2010

I created a custom vector type, inheriting from object, and defined __mul__,
__add__, etc. Unfortunately, the operators only work if I type "vector *
(int/float/number)", in that exact order. My program produces an error if I
instead type "number * vector". This makes sense to me, because I haven't
told the number (int, float, whatever) how to deal with an object of type
vector, (At least, I think that's why it doesn't work.). Is there any way
to allow "number (operator) vector", short of modifying the standard types'

Here's an example of the error.
vec1 = vector(5,6,7)
>>> vec1 * 2
(10, 12, 14)
>>> 2 * vec1
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    2 * vec1
TypeError: unsupported operand type(s) for *: 'int' and 'vector'

I'm using python 3.1.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100212/ad2c3da8/attachment.htm>

More information about the Tutor mailing list