[Tutor] overloading binary operator for mixed types: a no-no?
Alex Hunsley
lard at tardis.ed.ac.uk
Tue Nov 8 12:45:59 CET 2005
I'm writing a Vector class (think Vector as in the mathematical vector)...
A critical snippet is as follows:
class Vector(lister.Lister):
def __init__(self, *elems):
# ensure that we create a list, not a tuple
self.elems = list(elems)
def __add__(self, other):
return map(lambda x,y: x + y , self.elems, other.elems)
def __mult__(self, other):
return map(lambda x,y: x * y , self.elems, [other])
The overloading of + (add) works fine:
>>> a=Vector(1,2,3)
>>> a+a
[2, 4, 6]
But of course, I have problems with mult. When using vectors, it would
seem to make sense to overload the * (multiply) operator to mean
multiply a vector by a scalar as this would be the common usage in
maths/physics. (I've made a seperate method call dotProduct for dot
products for sake of clarity.)
Anyway, my multiply doesn't work of course:
>>> a=Vector(1,2,3)
>>> a * 2
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: unsupported operand type(s) for *: 'instance' and 'int'
... presumably because overloading binary operators like * requires that
both operands be instances of the class in question!
My question is: is there any way to overload * for my Vector class so
that notation like (a * 2) would work, and call __mult__ or similar? Or
should I just bite the bullet and write a normal method called
'multiply'? ('scale' would be better actually.)
thanks
alex
More information about the Tutor
mailing list