python - 如何制作两种不同的 __mul__ 方法

标签 python magic-methods

我构建了一个矩阵计算器并且 我想制作一个用于乘以标量的 mul 方法和另一个用于乘以其他矩阵的方法。我有一个 if-else block ,但我更喜欢它有两种不同的方法,但我希望它们都与 * operator 一起使用。我应该怎么做?

最佳答案

您可以使用 __mul__ (*) 和 __matmul__ (@) 或者,如果您想使用只有一个没有 if 的运算符,使用 singledispatchmethod(Python 3.8+)。

import functools

class Matrix:
    @functools.singledispatchmethod
    def __mul__(self, other):
        raise NotImplementedError(other)

    @__mul__.register
    def _(self, other: int):
        print('int')

    @__mul__.register
    def _(self, other: str):
        print('str')
Matrix() * 1 # 'int'
Matrix() * 'a' # 'str'

关于python - 如何制作两种不同的 __mul__ 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60981950/

相关文章:

python - aws boto3 抓取子网信息

python - scipy.optimize.minimize_scalar() 在目标函数内向辅助函数结果添加约束?

python - GeoPandas 绘图功能不起作用

python - 在python中为任何对象创建无穷大和负无穷大

php - 未定义函数的魔法?

python - 如何在 Windows 上导入 python26.zip

php - 如何记录 IDE 的魔法(_call 和 _callStatic)方法

python - 如何检查标识符是 dunder 还是 class-private(即会被破坏)?

php - PHP魔法方法的实际应用——__get、__set和__call

python - 未绑定(bind)本地错误 : local variable referenced before assignment