tags:

views:

41

answers:

4

I have a python class

class Vector2D(object):

    def __init__(self, x, y):
        self.x = float(x)
        self.y = float(y)

    def mag(self):
        return sqrt(self.x**2 + self.y**2)

    ...

I want to be able to multiply vectors together like vector1 * vector2, so I added

    def __mul__(self, v):
        return Vector2D(self.x * v.x, self.y * v.y)

But I also want to use new_vector = some_vector * 2 and return a new vector like so

    def __mul__(self, factor):
        return Vector2D(self.x * factor, self.y * factor)

How do I do both?

+2  A: 

Check to see if v is a Vector2D, and if not pass it to float() and multiply appropriately.

Ignacio Vazquez-Abrams
+1  A: 

There is no function overload in Python, you have to do it manually.

class Vector(object):
  def __init__(self, x, y):
    self.x = x
    self.y = y
  def __mul__(self, k):
    if type(k) == float or type(k) == int:
      return Vector(self.x * k, self.y * k)
    if type(k) == Vector:
      return Vector(self.x * k.x, self.y * k.y)
    raise "What the hell!?"
  def __str__(self):
    return "<%f, %f>" % (self.x, self.y)


print Vector(1, 2) * Vector(3, 4)
print Vector(1, 2) * 5
Evgeny
is it better to use `type` or `isinstance`?
colinmarc
@colinmarc: `type()` checks for a specific type. `isinstance()` will catch subclasses.
Ignacio Vazquez-Abrams
Also, comparing the type to `float` or `int` will miss other types that implement number-like behavior.
Ignacio Vazquez-Abrams
(And for the reason you explain, `isinstance` is preferred to `type(...) ==` in almost all the (rare) cases where you do want to typecheck.)
Mike Graham
raising a string has been deprecated for a very, very, very, very, very long time.
Mike Graham
A: 

I'm not incredible with Python, but I'm pretty sure you just write one function and check the type of the second argument.

By the way, why are you multiplying vectors by just multiplying their components? That seems entirely useless.

Joseph Torres
it's more of an example. I'm also overriding `__add__`, `__sub__`, `__lt__`, etc and I wanted to know how to operate on it with other vectors as well as regular numbers
colinmarc
A: 

Consider that you might want to use numpy for this sort of data.

Mike Graham
I really want to avoid extra dependencies
colinmarc