Python 如何制作两种不同的方法
我建立了一个矩阵计算器和Python 如何制作两种不同的方法,python,magic-methods,Python,Magic Methods,我建立了一个矩阵计算器和 我想用一个mul方法进行标量乘法,另一个方法进行其他矩阵乘法。我有一个if-else块,但我更喜欢用两种不同的方法,但我希望它们都使用*操作符。我应该怎么做呢?您可以使用\uuuuMul\uUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUu 导入工具
我想用一个mul方法进行标量乘法,另一个方法进行其他矩阵乘法。我有一个if-else块,但我更喜欢用两种不同的方法,但我希望它们都使用*操作符。我应该怎么做呢?您可以使用
\uuuuMul\uUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUuUu
导入工具
类别矩阵:
@functools.singledispatchmethod
定义多个(自身、其他):
引发未实施错误(其他)
@__多重寄存器
定义(自身,其他:int):
打印('int')
@__多重寄存器
定义(自身、其他:str):
打印('str')
Matrix()*1#'int'
矩阵()*'a'#'str'
functools.singledispatchmethod
似乎适合您所描述的内容。另一个示例使用参数注释指定类型,也可以将它们指定为装饰器的参数:
>>> class Foo:
... def __init__(self, value):
... self._value = value
...
... @functools.singledispatchmethod
... def __mul__(self, other):
... print("hmm...")
...
... @__mul__.register(int)
... def _(self, other):
... print("Using the int version.")
... return self._value * other
...
... @__mul__.register(list)
... def _(self, other):
... print("Using the list version.")
... return [item * self._value for item in other]
...
>>> f = Foo(8)
>>> f * 3
Using the int version.
24
>>> f * [1, 2, 3]
Using the list version.
[8, 16, 24]
如果使用早于3.8的Python版本(在本例中,最好只在单个方法中执行类型检查,而不使用decorator):
使用\uuuuuuuuuuuu
(*
)和\uuuuuuuuuuuuuu
(@
)。功能工具。我想到了singledispatch
。大家好,欢迎来到StackOverflow!您在这里询问的是\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
,但这篇关于\uuuuuuuuuuuuuuuuuuuuuu。尽管遗憾的是,那里的解决方案似乎无法帮助您定义两种不同的方法。
>>> class Foo:
... def __init__(self, value):
... self._value = value
... self.mul = functools.singledispatch(self.mul)
... self.mul.register(int, self.mul_int)
... self.mul.register(list, self.mul_list)
...
... def __mul__(self, other):
... return self.mul(other)
...
... def mul(self, other):
... print("Default mul() called.")
...
... def mul_int(self, other):
... print("Using the int version.")
... return self._value * other
...
... def mul_list(self, other):
... print("Using the list version.")
... return [item * self._value for item in other]
...
>>> f = Foo(3)
>>> f * 7
Using the int version.
21
>>> f * [1, 2, 3]
Using the list version.
[3, 6, 9]
>>>