Overloading Addition, Subtraction, and Multiplication Operators

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]

Solution 1:

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.

Solution 2:

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

Solution 3:

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.