Singledispatch decorator不能像广告中所宣传的那样工作

2024-10-05 14:29:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在测试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

Tags: httpsdivregisterlendefblockintdispatch
1条回答
网友
1楼 · 发布于 2024-10-05 14:29:48

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)
    ...

相关问题 更多 >