我正在测试 python 的 singledispatch
:https://docs.python.org/3/library/functools.html?highlight=singledispatch#functools.singledispatch
根据文档, block A 应该和 block B 一样工作。但是,您可以在输出中看到只有 block B 按预期工作。
这里有什么问题吗?谢谢。
from functools import singledispatch
# Block A
@singledispatch
def divider(a, b=1):
print(a, b)
@divider.register
def _(a: int, b=1):
print(a/b)
@divider.register
def _(a: str, b=1):
print(a[:len(a)//b])
divider(25, 2)
divider('single dispatch practice', 2)
# Block B
@singledispatch
def div(a, b=1):
print(a, b)
@div.register(int)
def _(a: int, b=1):
print(a/b)
@div.register(str)
def _(a: str, b=1):
print(a[:len(a)//b])
div(25 , 2)
div('single dispatch practice', 2)
输出:
>> 25 2
>> single dispatch practice 2
>> 12.5
>> single dispatch
最佳答案
I am testing python's singledispatch (...) What's is the problem here?
您使用类型注释是正确的,但是@singledispatch
仅使用它们since Python 3.7 (注释在 Python 3.0 中引入,singledispatch 在 3.4 中引入)。因此
# works since 3.4
@foo.register(str)
def foo_str(a: str):
...
# works since 3.7
@foo.register
def foo_str(a: str)
...
关于python - Singledispatch 装饰器并不像宣传的那样工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51114481/