Overloading operators of addition, subtraction and multiplication

How do you overload the operation of addition, subtraction and multiplication so that we can add, subtract and multiply two vectors of different or identical sizes? For example, if the vectors have different sizes, should we be able to add, subtract or multiply two vectors according to the smallest vector size?

I created a function that allows you to change different vectors, but now I'm struggling to overload the operators and do not know where to start. I will insert 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] 
+7
operators python class vector
source share
3 answers

You will define the __add__ , __sub__ and __mul__ for this class. Each method takes two objects (operands + / - / * ) as arguments and is expected to return the result of the calculation.

+12
source share

docs is the answer. Basically there are functions called by the object when you add or more, etc., For example, __add__ is a normal add function.

+4
source share

There is nothing wrong with the accepted answer to this question, but I am adding a few quick snippets to illustrate how this can be used. (Note that you can also β€œoverload” several types of processing methods.)


 """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 
+1
source share

All Articles