Python Glossary Русский

all Python 3OOPfunction

__mul__

magic methods

The method behind *: a * b calls a.__mul__(b); the reflected __rmul__ handles 3 * a.

Syntax

def __mul__(self, other): ...
def __rmul__(self, other): ...

Multiplying by a number on either side needs two methods: __mul__ for v * 3 and __rmul__ for 3 * v — int has no way to multiply by your object and returns NotImplemented. Sequences use __mul__ for repetition: [0] * 3 is list.__mul__.

Examples

class Vec:
    def __init__(self, x, y):
        self.x, self.y = x, y
    def __mul__(self, k):
        return Vec(self.x * k, self.y * k)
    __rmul__ = __mul__
    def __repr__(self):
        return f'Vec({self.x}, {self.y})'
print(Vec(1, 2) * 3)  # → Vec(3, 6)
print(3 * Vec(1, 2))  # → Vec(3, 6) — сработал __rmul__

See also

Open in the full glossarydocs.python.orgReport an inaccuracy