python - 如何修改算术运算符 (+,-,x)

标签 python

我目前正在为 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/

相关文章:

python - 这段代码 : %(var)s ? Python 可能是什么?

python - 在 python 中以交互方式显示 matplotlib 中的图形

python - Scrapy:从分页中抓取数据

python - PIP无法安装auto-py-to-exe

python - 按 '1' 按钮后缩放停止工作,但仅限于子图中

python - 多处理卡住计算机

python - 多线程socket程序-处理临界区

Python 快速读取多行 csv 文本的方法?

python - mysql.connector 和常规 MySQL 中的精确查询不返回相同的结果

python - 如何在 virtualenv 中强制使用新版本的 Django?