如何使“ class1 * class2”表现得像“ class2 * class1”?

时间:2019-08-25 18:06:54

标签: python class oop

我一直在看Linear Algebra制作的3Blue1Brown系列,我想到了我应该编写程序来计算数学的想法,所以我开始做。

我写了一些方法。我为此写了mul方法。这种方法可以将向量拉伸给定因子。

class Vector:
    def __init__(self, data):
        #               [1]
        # [1, 2, 3] --> [2]
        #               [3]
        self.data = data
    def __mul__(self, other):
        if not isinstance(other, (int, float)):
            raise TypeError("The second object(item) is not a number(integer, float)")
        return Vector(list(map(lambda x: x * other, self.data)))

例如:

sample = Vector([1, 2])

当我执行此操作时,它会正确执行:

print(sample * 10)
# it returns Vector([10, 20])

但是当我执行此操作时:

print(10 * sample)

它抛出一个错误:

Traceback (most recent call last):
  File "/home/jackson/Desktop/Matrices/MM.py", line 139, in <module>
    print(10 * a)
TypeError: unsupported operand type(s) for *: 'int' and 'Vector'

我知道第二个是int。 mul 。那么,第二种人有没有办法像第一种一样?因为从技术上讲,“ Vector * int”和“ int * Vector”之间应该没有任何区别。

如果需要,这里是完整的代码-> link

1 个答案:

答案 0 :(得分:3)

是的,您需要实现__rmul__等。请参见https://docs.python.org/3.7/reference/datamodel.html#emulating-numeric-types

此外,对于python,已经存在一个非常好的线性代数库,名为numpy(但是,如果您出于学习目的自己实现该代数,就可以忽略它而取乐)。