For example, what should I do when I want to execute a constant multiple of the "Point class" that is often given as an example? As an example
class Point():
def __init__(self,x,y):
self.x = x
self.y = y
Let's define multiplication though. As a specification, let's assume that when multiplying points, a Point type that multiplies by x and y is returned, and when multiplying with an integer, a Point type that is multiplied by a constant is returned.
First, define the operation with \ _ \ _ mul__
class Point():
...
def __mul__(self, other):
if isinstance(other,Point):
return Point(self.x*other.x,self.y*other.y)
elif isinstance(other,int):
return Point(self.x*other,self.y*other)
else:
return NotImplemented
...
Since this alone does not support operations from the right, use \ _ \ _ rmul__ For example, if mul is defined in an operation that holds the commutative law.
def __rmul__(self,other):
return self*other
But it's okay if you write If you want to use other * = etc., you can call \ _ \ _ imul__.
Recommended Posts