如何让"class1 * class2"表现得像"class2 * class1"?

  • 本文关键字:class1 class2 python class oop
  • 更新时间 :
  • 英文 :


我一直在看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"之间不应该有任何区别。

如果您需要,这是完整的代码 -->链接

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

此外,Python 已经存在一个非常好的线性代数库,称为 numpy(但如果您出于学习目的自己实现它,请忽略它并享受乐趣(。

最新更新