1

I have a vector class which gives a vector with a list and I need to be able to add vectors or vectors to lists, tuples, and strings. If they are not of the same length, I need to throw a type error. Some examples of output:

Vector([6,8,2])+Vector([4,-3,2])
Vector([10, 5, 4])
>>> Vector([6,8,2])+[4,-3,2]
Vector([10, 5, 4])
>>> (6,8,2)+Vector([4,-3,2])
Vector([10, 5, 4])
>>> v=Vector(["f","b"])
>>> v+=("oo","oo")
>>> v
Vector(['foo', 'boo'])

I need to make a + function and a += function.

Which python methods do I use to override the + and += operations, also I need to make sure that my + operation works on an object and a sequence and the reverse

Anatoliy Sokolov
  • 347
  • 1
  • 4
  • 10
  • you can check the type of the `other` argument by with `isinstance`, e.g., `isinstance(other, Vector)` – Elmar Peise Mar 01 '16 at 23:28
  • I think the `__iadd__` method is what you're looking for (for the += case). http://stackoverflow.com/questions/1047021/overriding-in-python-iadd-method – Garrett R Mar 01 '16 at 23:39
  • I made iadd work for 2 vectors and Im not sure why it doesn work for a vector and a sequence >>> v=Vector(["f","b"]) >>> v+=("oo","oo") Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for +=: 'instance' and 'tuple' >>> – Anatoliy Sokolov Mar 01 '16 at 23:49

1 Answers1

1

To fully implement concatenation in arbitrary order, you need to implement three methods, __add__, __radd__ and __iadd__. You didn't implement __add__ at all (so Vector + sequence doesn't work, only sequence + Vector using __radd__) and you misspelled __iadd__ as __iadd (so Vector += anything doesn't work).

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • Oh I didnt notice that. I kind of get it I put in add with the same exact implementation as radd and it worked. – Anatoliy Sokolov Mar 02 '16 at 00:02
  • @AnatoliySokolov: The basic rule is that the plain `__xxx__` method for binary operators is called when the instance is on the left side of the operator, `__rxxx__` is called when it is on the right side and the object on the left side's `__xxx__` didn't exist (or returned `NotImplemented`), and `__ixxx__` is called when using the augmented assignment operator. `__ixxx__` is optional; for immutable types, Python uses `__xxx__` when `__ixxx__` is missing. You may want to look at the [`collections.abc` interfaces](https://docs.python.org/3/library/collections.abc.html#module-collections.abc) – ShadowRanger Mar 02 '16 at 00:22
  • @AnatoliySokolov: You may also want to look at [Implementing the arithmetic operations](https://docs.python.org/3/library/numbers.html#implementing-the-arithmetic-operations) for tips on using an operator fallback based approach to avoiding lots of repetitious code; it's focused mathematical operations, but the same techniques apply to sequence operations, and the example given from `fractions.Fraction` can shorten code a lot. – ShadowRanger Mar 02 '16 at 00:29