如何使我的重载运算符在Python中使用内置类型正确运行?

时间:2012-06-01 18:23:13

标签: python oop

感觉就像这么简单,但我似乎找不到我需要的信息。 假设我定义了一个类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.

如果我用矩阵乘以矩阵,这个工作正常,但由于int不知道如何处理矩阵,3 * Matrix引发了一个TypeError。 我该如何处理?

2 个答案:

答案 0 :(得分:4)

定义__rmul__以覆盖int() __mul__方法的调用:

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

请注意can do this with all of the numeric operators

另请注意,最好使用新的样式类,因此请将您的类定义为:

class Matrix(object):

这将允许您执行以下操作:

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

答案 1 :(得分:1)

定义__rmul__()方法。