Alex Hunsley wrote:
> 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)

Don't you want this to return a new Vector, rather than a list? So for example 
you can add three vectors a + b + c?

Instead of defining your own function, you can use operator.add(). So I would 
write this as
  return Vector(map(operator.add, self.elems, other.elems))

>     def __mult__(self, other):
>         return map(lambda x,y: x * y , self.elems, [other])

This could be map(lambda x: x * other, self.elems) or [ x * other for x in 
self.elems ]

> 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!

No, actually it is because you have misspelled __mul__!

You might also want to implement __rmul__() so you can write 2 * a. See this 
page for a list of all special methods for numeric types:
http://docs.python.org/ref/numeric-types.html

Do you know about Numeric and numpy? They are high-performance implementations 
of arrays that support operations like these. You should probably look into 
them.

Kent

-- 
http://www.kentsjohnson.com

_______________________________________________
Tutor maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/tutor

Reply via email to