【发布时间】:2018-06-30 11:27:00
【问题描述】:
我正在测试python的singledispatch:https://docs.python.org/3/library/functools.html?highlight=singledispatch#functools.singledispatch
根据文档,A 块应该和 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
【问题讨论】:
-
你用的是什么版本的python?类型注释功能是 Python 3.7 中的新功能
-
谢谢。我将 python 解释器更改为 3.7,现在它可以工作了!
-
@PatrickHaugh 实际上类型注释是在 3.0 中引入的,但是
@singledispatch从 3.7 开始只使用 docs.python.org/3/whatsnew/3.7.html#functools -
@miraculixx 这就是我所说的“类型注释功能”。我想这有点不清楚。