title: How can I overload operators so that type on the left/right does not matter?
body: <p>A simple example - I want to have a point class that describes a point in 2 dimensions. And I want to be able to add two points together... as well as multiply two points together (don't ask me why), or multiply a point by a scalar. For right now, I'll only implement it as if the scalar is an integer but fraction or floats is also trivial to do.</p>
  
  <pre><code>class Point:
      def __init__(self, x=0, y=0):
          self.x = x
          self.y = y
  
      def __str__(self):
          return "({0},{1})".format(self.x, self.y)
  
      def __add__(self, other):
          x = self.x + other.x
          y = self.y + other.y
          return Point(x, y)
  
      def __mul__(self, other):
          if isinstance(other, Point):
              x = self.x * other.x
              y = self.y * other.y
              return Point(x, y)
          elif isinstance(other, int):
              x = self.x * other
              y = self.y * other
              return Point(x, y)
  </code></pre>
  
  <p>So, this works when I perform:</p>
  
  <pre><code>&gt;&gt;&gt; p1 = Point(2, 3)
  &gt;&gt;&gt; p2 = Point(-1, 2)
  &gt;&gt;&gt; print(p1*p2)
  (-2,6)
  &gt;&gt;&gt;print(p1*4)
  (8,12)
  </code></pre>
  
  <p>but it does NOT work when I reverse the order of scalar and Point object:</p>
  
  <pre><code>&gt;&gt;&gt;print(4*p1)
  Traceback (most recent call last):   
    File "&lt;input&gt;", line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for *:
  'int' and 'Point'
  </code></pre>
  
  <p>How can I write the code where it doesn't matter if I write '4 * p1' or 'p1 * 4' that I'll still execute the same code and return the same answer? Do I accomplish this by overloading the <strong>mul</strong> operator for int objects or is there another way?</p>
  
  <p>Note: code for my short example was borrowed from <a href="https://www.programiz.com/python-programming/operator-overloading" rel="noreferrer">https://www.programiz.com/python-programming/operator-overloading</a></p>