2

I have a class

class Vector():
    def __init__(self, *args):
        self.coords = list(args)
    def __add__(self, other):
        temp = []
        for i in range(len(self)):
            tmp.append(self[i] + other[i])
        print(str(tmp))
        return Vector(*tmp)
    def __getitem__(self, key):
        return self.coords[key]

The goal is to make Vector class objects behave like vectors. I want do the addition operations like this

list = [0, 1, 2, 3]
v1 = Vector(3, 2, 1, 0)
result1 = v1 + list
result2 = list + v1

and get this results:

result1 = Vector(3, 3, 3, 3)
result2 = Vector(3, 3, 3, 3)

When i defined the getitem method, Vector class started support indexing and result1 is correct. But result 2 returns TypeError: can only concatenate list (not "Vector") to list. I ran out of ideas what should I looking for to resolve this.

kubablo
  • 83
  • 2
  • 9
  • 4
    You should define `__radd__` as well. – Daniel Roseman Nov 11 '17 at 21:17
  • 1
    And have a look at `zip`. `range(len(...))` is always ugly. – timgeb Nov 11 '17 at 21:18
  • 1
    `tmp = [a+b for a,b in zip(self,other)]`, and that will protect from index out of range :) – Jean-François Fabre Nov 11 '17 at 21:20
  • 1
    Works perfect. Shame on my observation instinct. I was searching in documentation and overlooked the r-methods. Thank You. – kubablo Nov 11 '17 at 21:25
  • By the way, implementing a `__getitem__` method makes your vectors iterable, (so `for x in self:` loops work) but it's a legacy feature of the language. Consider implementing `__iter__`. [This](https://stackoverflow.com/questions/1952464/in-python-how-do-i-determine-if-an-object-is-iterable/36407550#36407550) post has more information. – timgeb Nov 11 '17 at 21:36

0 Answers0