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.

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.

Practice

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.

💻 Template code

Solution code

Vector

Have your teacher walk you through this one.