13.3 Mathematical Operators

Mathematical Operators

Next, you can also define mathematical operators for classes as well. In fact, all operators which are supported by Python involving integers can also be customized for our own classes. For simplicity’s sake, we will only go over a few key mathematical operators which will be useful for our classes. All operators take two arguments: self and another variable which we are multiplying the object to.
  • __pow__ - implements the power operator for this class (**)
  • __add__ - implements the addition operator for this class (+)
  • __sub__ - implements the subtraction operator for this class (-)
  • __mul__ - implements the multiplication operator for this class (*)
Here's an example:
class Vector: def __init__(self, vals): """ Constructor self: a reference to the object we are creating vals: a list of integers which are the contents of our vector """ self.vals = vals # print("Assigned values ", vals, " to vector.") def __str__(self): """ String Function Converts the object to a string in readable format for programmers """ return str(self.vals) def __pow__(self, power): """ Elementwise power: raises each element in our vector to the given power """ return Vector([i ** power for i in self.vals]) def __add__(self, vec): """ Addition: adds each element to corresponding element in other vector """ return Vector( [self.vals[i] + vec.vals[i] for i in range(len(self.vals))] ) def __mul__(self, constant): """ Multiplies each element in the vector by a specified constant """ return Vector([self.vals[i] * constant for i in range(len(self.vals))]) def __sub__(self, vec): """ Elementwise subtraction: does same as addition, just subtraction instead """ return self + (vec * (-1)) vec = Vector([2, 3, 2]) otherVec = Vector([3, 4, 5]) print(str(vec)) # [2, 3, 2] print(vec ** 2) # [4, 9, 4] print(vec - otherVec) # [-1, -1, -3] print(vec + otherVec) # [5, 7, 7] print(vec * 5) # [10, 15, 10]
View code on GitHub.
Observe however that the multiply operation for Vector can function correctly only if the vector goes first in the multiplication expression(I.e. Vector * Integer will function perfectly). However, its commutative, Integer * Vector will not work. This is because the first argument in the expression is the one whose __mul__ method is called, and the Integer type in Python obviously doesn’t support multiplying our custom class object with it. We will need to define it ourselves. There is a workaround for this, but we will not cover it in this section. This is just to demonstrate how __mul__ can be implemented.


Matrix Add Subtract

Have your teacher walk you through this one.
Write a modified version of the Matrix class(that was defined in one of the example problems in this section) with an __add__ operation as well as a __sub__ operation. It should add matrices, assuming that they will be of the same length. Also, the unmodified Matrix class code will be given.


Have your teacher walk you through this one.
Define a Vector class so that the multiply operation is with another Vector instead. The multiply operation should be the inner or dot product of the two vectors. That means that each element in the vector should be multiplied with its corresponding element in the other vector, and then summed. A scalar (regular number) should be returned.


Write a class called Triangle which will take three tuples (each tuple contains two integers: the x and y coordinates of a vertex). Then, define an __add__ operation that acts as a translation operation. Its input argument will be a tuple of two integers that will indicate the x and y translations that will be applied to each coordinate. (basically, add the tuple to each coordinate of the triangle). Also, define a vertical and horizontal transformation tool in the form of __mul__ which will also take a tuple of two integers that will be multiplied to the x and y coordinates of each vertex respectively.
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.