我目前正在为 Python 3.x 编写线性代数模块,其中我处理自定义矩阵对象。
有什么方法可以使 +、-、* 等基本算术运算符与我的矩阵对象保持一致?例如-
>>> A = matrix("1 2;3 4")
>>> B = matrix("1 0; 0 1")
>>> A + B
[2 2]
[3 5]
>>> A * A
[7 10]
[15 22]
现在我已经为加法、乘法等编写了单独的函数,但是输入 A.multiply(A)
比简单地输入 A*A
麻烦得多。
最佳答案
您正在寻找special methods .特别是在 emulating numerical types section .
此外,当您尝试实现矩阵并且矩阵是容器时,您可能会发现定义自定义 container methods 很有用。适合您的类型。
更新:这是一个使用特殊方法实现算术运算符的自定义对象示例:
class Value(object):
def __init__(self, x):
self.x = x
def __add__(self, other):
if not isinstance(other, Value):
raise TypeError
return Value(self.x + other.x)
def __mul__(self, other):
if not isinstance(other, Value):
raise TypeError
return Value(self.x * other.x)
assert (Value(2) + Value(3)).x == 5
assert (Value(2) * Value(3)).x == 6
关于python - 如何修改算术运算符 (+,-,x),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23954758/