Roman Levin
Roman Levin

Reputation: 461

How do I make my overloaded operators behave correctly with built-in types in Python?

It feels like such a simple thing but I can't seem to find the info I need. Say I define a class Matrix:

class Matrix():
    def __mul__(self, other):
    if isinstance(other, Matrix):
        #Matrix multiplication.
    if isinstance(other, int): #or float, or whatever
        #Matrix multiplied cell by cell.

This work fine if I multiply a matrix by an int, but since int doesn't know how to deal with matrices, 3*Matrix raises a TypeError. How do I deal with this?

Upvotes: 3

Views: 123

Answers (2)

Joel Cornett
Joel Cornett

Reputation: 24788

Define __rmul__ to override the calling of int()'s __mul__ method:

class Matrix():
    # code

    def __rmul__(self, other):
        #define right multiplication here.

        #As Ignacio said, this is the ideal
        #place to define matrix-matrix multiplication as __rmul__() will
        #override __mul__().

    # code

Note that you can do this with all of the numeric operators.

Also note that it's better to use new style classes, so define your class as:

class Matrix(object):

This will allow you to do things like:

if type(other) == Matrix: ...

Upvotes: 4

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798804

Define the __rmul__() method as well.

Upvotes: 1

Related Questions