我构建了一个矩阵计算器并且 我想制作一个用于乘以标量的 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/