我正在测试python的singledispatch
:https://docs.python.org/3/library/functools.html?highlight=singledispatch#functools.singledispatch
根据文件,A区应该和B区一样工作。但是,您可以在输出中看到,只有块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
使用类型注释是正确的,但是
@singledispatch
只使用类型注释since Python 3.7(注释是在Python 3.0中引入的,singledispatch是在3.4中引入的)。因此相关问题 更多 >
编程相关推荐