37

How do you go about overloading the addition, subtraction, and multiplication operator so we can add, subtract, and multiply two vectors of different or identical sizes? For example, if the vectors are different sizes we must be able to add, subtract, or multiply the two vectors according to the smallest vector size?

I've created a function that allows you to modify different vectors, but now I'm struggling to overload the operators and haven't a clue on where to begin. I will paste the code below. Any ideas?

def __add__(self, y):
    self.vector = []
    for j in range(len(self.vector)):
        self.vector.append(self.vector[j] + y.self.vector[j])
    return Vec[self.vector]
martineau
  • 119,623
  • 25
  • 170
  • 301
user3014014
  • 751
  • 3
  • 10
  • 20

3 Answers3

48

You define the __add__, __sub__, and __mul__ methods for the class, that's how. Each method takes two objects (the operands of +/-/*) as arguments and is expected to return the result of the computation.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
jwodder
  • 54,758
  • 12
  • 108
  • 124
  • okay, i understand that now. thank you. how do i actually define them in this code? `self.vector[index].__add__(self, x)`??? – user3014014 Dec 10 '13 at 23:57
  • 1
    @user3014014: The same way you defined the other methods; just stick them in the class definition. – jwodder Dec 10 '13 at 23:58
  • would `def __add__(self, x, y)` have 2 arguments like this? – user3014014 Dec 11 '13 at 00:09
  • 4
    @user3014014: No; it's `def __add__(self, y)`. The `self` is the left operand to `+`. – jwodder Dec 11 '13 at 00:10
  • You may want to take a look at the [`fractions`](http://docs.python.org/2/library/fractions.html) module. Notice the link to the source right at the top. That's because it's intended to be used as sample code for writing your own numeric classes. It may look a lot more complicated than you need, but if you actually want to emulate all of the operators, and to be able to work with scalar values (so `myvec * 2` or `2 * myvec` works), and so on, the "complicated" way is actually easier than copying and pasting all the fiddly bits dozens of times. – abarnert Dec 11 '13 at 00:15
  • `def __add__(self, y): z = self.vector.__add__(y) return z` Is this anywhere near correct? – user3014014 Dec 11 '13 at 00:22
  • @user3014014: Only the part up to the colon is correct. Maybe you should start by writing a function that performs vector addition on lists and then adapt it to the `Vec` class. – jwodder Dec 11 '13 at 00:24
  • I've made an add function that i believe should work, but i'm getting a `TypeError`. What's wrong here? – user3014014 Dec 11 '13 at 01:03
  • 1
    And to divide, use `__truediv__`. See https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types for more. – cowlinator Feb 12 '20 at 03:59
17

Nothing wrong with the accepted answer on this question but I'm adding some quick snippets to illustrate how this can be used. (Note that you could also "overload" the method to handle multiple types.)


"""Return the difference of another Transaction object, or another 
class object that also has the `val` property."""

class Transaction(object):

    def __init__(self, val):
        self.val = val

    def __sub__(self, other):
        return self.val - other.val


buy = Transaction(10.00)
sell = Transaction(7.00)
print(buy - sell)
# 3.0

"""Return a Transaction object with `val` as the difference of this 
Transaction.val property and another object with a `val` property."""

class Transaction(object):

    def __init__(self, val):
        self.val = val

    def __sub__(self, other):
        return Transaction(self.val - other.val)


buy = Transaction(20.00)
sell = Transaction(5.00)
result = buy - sell
print(result.val)
# 15

"""Return difference of this Transaction.val property and an integer."""

class Transaction(object):

    def __init__(self, val):
        self.val = val

    def __sub__(self, other):
        return self.val - other


buy = Transaction(8.00)
print(buy - 6.00)
# 2
Michelle Welcks
  • 3,513
  • 4
  • 21
  • 34
7

docs have the answer. Basically there are functions that get called on an object when you add or multiple, etc. for instance __add__ is the normal add function.

cmd
  • 5,754
  • 16
  • 30