Python __mul__ Method
Last modified November 18, 2026 Python 3.15
The * operator calls __mul__ on its left operand.
A class can give it a numeric meaning such as scaling a vector, or a
container meaning such as repetition. This article covers scalar products,
element-wise products, the reflected __rmul__ method, mixed
types, the built-in repetition rule, the distinction from @,
and operator.mul.
Basic multiplication
The hook receives the right operand and returns the product. Returning
NotImplemented for an unsupported type lets Python try the
reflected method or raise TypeError.
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __mul__(self, scalar):
if isinstance(scalar, (int, float)):
return Vector(self.x * scalar, self.y * scalar)
return NotImplemented
def __repr__(self):
return f"Vector({self.x}, {self.y})"
v = Vector(2, 3)
print(v * 3)
print(v * 0.5)
Multiplying by 3 scales both components, and multiplying by a float keeps the float results. The hook built a new vector each time rather than changing the original.
$ python basic_mul.py Vector(6, 9) Vector(1.0, 1.5)
Commutative multiplication with __rmul__
When the left operand is a number, Python tries
number.__mul__(vector) first. That fails, so it calls
vector.__rmul__(number). Implementing the reflected method makes
both spellings work.
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __mul__(self, scalar):
if isinstance(scalar, (int, float)):
return Vector(self.x * scalar, self.y * scalar)
return NotImplemented
def __rmul__(self, scalar):
return self.__mul__(scalar)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
v = Vector(2, 3)
print(v * 3)
print(3 * v)
Both expressions give the same result. Delegating
__rmul__ to __mul__ is correct for scalar
multiplication because it is commutative — that would not be true for every
operator.
$ python rmul.py Vector(6, 9) Vector(6, 9)
Element-wise products
When both operands are vectors, the hook can multiply matching components.
This is a different meaning of * from scaling by a number, and
it needs its own length check.
class Vector:
def __init__(self, *components):
self.components = list(components)
def __mul__(self, other):
if isinstance(other, (int, float)):
return Vector(*[x * other for x in self.components])
if isinstance(other, Vector):
if len(self.components) != len(other.components):
raise ValueError("vectors must have the same length")
return Vector(*[a * b for a, b in zip(self.components,
other.components)])
return NotImplemented
def __repr__(self):
return f"Vector{self.components}"
v1 = Vector(1, 2, 3)
v2 = Vector(4, 5, 6)
print(v1 * v2)
print(v1 * 2)
try:
Vector(1, 2) * v2
except ValueError as e:
print(type(e).__name__, e)
Component products are 1*4, 2*5 and 3*6, giving 4, 10 and 18. Scaling still works. Vectors of unequal length are rejected before any multiplication.
$ python elementwise.py Vector[4, 10, 18] Vector[2, 4, 6] ValueError vectors must have the same length
Different results for different types
A single hook can choose its behaviour from the operand type. Multiplying a length by a number scales it; multiplying two lengths returns a plain number representing an area.
class Meter:
def __init__(self, value):
self.value = value
def __mul__(self, other):
if isinstance(other, (int, float)):
return Meter(self.value * other)
if isinstance(other, Meter):
return self.value * other.value
return NotImplemented
def __rmul__(self, other):
return self.__mul__(other)
def __repr__(self):
return f"{self.value}m"
distance = Meter(5)
print(distance * 2)
print(3 * distance)
area = distance * Meter(4)
print(area, type(area).__name__)
The first two results are still lengths, while multiplying two lengths produces the integer 20 — an area in square metres. Returning a different type is fine here because the meaning genuinely changes.
$ python units.py 10m 15m 20 int
Falling back to the reflected method
When __mul__ returns NotImplemented, Python asks
the right operand's __rmul__. That is how a custom object can be
multiplied by a type it knows nothing about.
class Other:
def __rmul__(self, left):
print("Other.__rmul__")
return "reflected result"
def __repr__(self):
return "Other()"
class Vector:
def __init__(self, *parts):
self.parts = list(parts)
def __mul__(self, other):
if not isinstance(other, (int, float)):
return NotImplemented
return Vector(*[p * other for p in self.parts])
def __repr__(self):
return f"Vector{self.parts}"
print(Vector(1) * Other())
Vector.__mul__ declined the Other object, so
Other.__rmul__ supplied the answer. If both sides decline,
Python raises TypeError instead.
$ python reflected_mul.py Other.__rmul__ reflected result
Repetition and @ are different operations
Built-in sequences use * for repetition, not numeric product.
Matrix-style products use the separate @ operator, which calls
__matmul__. The two must not be confused.
class Matrix:
def __init__(self, rows):
self.rows = [list(row) for row in rows]
def __matmul__(self, other):
return Matrix([
[sum(a * b for a, b in zip(row, col))
for col in zip(*other.rows)]
for row in self.rows
])
def __repr__(self):
return f"Matrix({self.rows})"
print([1, 2] * 3)
print(3 * "ab")
a = Matrix([[1, 2], [3, 4]])
b = Matrix([[5, 6], [7, 8]])
print(a @ b)
A list and a string repeat their contents; the matrices use
@ for a true matrix product. Since Matrix has no
__mul__, writing a * b would raise
TypeError.
$ python star_vs_at.py [1, 2, 1, 2, 1, 2] ababab Matrix([[19, 22], [43, 50]])
The operator.mul function
operator.mul(a, b) is the functional form of a * b.
It calls the same hook and is useful when a callable is needed.
import operator
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
print(operator.mul(Vector(2, 3), 4))
print(operator.mul(6, 7))
The custom vector and the plain integers both dispatch through their own implementations. The functional form gives exactly the same results as the operator syntax.
$ python operator_mul.py Vector(8, 12) 42
Best practices
A few rules keep * predictable:
- Return
NotImplementedfor operand types you do not support. - Implement
__rmul__when the operands may be swapped. - Validate lengths before computing element-wise products.
- Document when the result type changes, such as a length times a length producing an area.
- Use
@and__matmul__for matrix products, not*.
Source
object.__mul__ - Python documentation
Emulating numeric types - Python documentation
operator.mul - Python documentation
Common sequence operations - Python documentation
In this article we have implemented the __mul__ method. We have
covered scalar and element-wise products, reflected multiplication, mixed
types, sequence repetition, the difference from @ and
operator.mul. For related topics, see
Python __matmul__ method,
Python __imul__ method, and
Python operators.
Author
List all Python tutorials.