Overloading Addition, Subtraction, and Multiplication Operators

60,913

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.

Share:
60,913
user3014014
Author by

user3014014

Updated on July 20, 2022

Comments

  • user3014014
    user3014014 almost 2 years

    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]
    
  • user3014014
    user3014014 over 10 years
    okay, i understand that now. thank you. how do i actually define them in this code? self.vector[index].__add__(self, x)???
  • jwodder
    jwodder over 10 years
    @user3014014: The same way you defined the other methods; just stick them in the class definition.
  • user3014014
    user3014014 over 10 years
    would def __add__(self, x, y) have 2 arguments like this?
  • jwodder
    jwodder over 10 years
    @user3014014: No; it's def __add__(self, y). The self is the left operand to +.
  • abarnert
    abarnert over 10 years
    You may want to take a look at the fractions 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.
  • user3014014
    user3014014 over 10 years
    def __add__(self, y): z = self.vector.__add__(y) return z Is this anywhere near correct?
  • jwodder
    jwodder over 10 years
    @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.
  • user3014014
    user3014014 over 10 years
    I've made an add function that i believe should work, but i'm getting a TypeError. What's wrong here?
  • cowlinator
    cowlinator about 4 years
    And to divide, use __truediv__. See docs.python.org/3/reference/… for more.