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

3
  • you can check the type of the other argument by with isinstance, e.g., isinstance(other, Vector) Commented Mar 1, 2016 at 23:28
  • I think the __iadd__ method is what you're looking for (for the += case). stackoverflow.com/questions/1047021/… Commented Mar 1, 2016 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 "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +=: 'instance' and 'tuple' >>> Commented Mar 1, 2016 at 23:49

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

3 Comments

Oh I didnt notice that. I kind of get it I put in add with the same exact implementation as radd and it worked.
@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
@AnatoliySokolov: You may also want to look at 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.