使用kwargs重载multipledispatch的python方法

2024-06-18 08:41:35 发布

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

我使用python3.8和multipledispatch库来重载方法签名

multipledispatch文档示例建议如下重载:

from multipledispatch import dispatch


@dispatch(int, int)
def add(x, y):
    print(x + y)


@dispatch(str, str)
def add(x, y):
    print(f'{x} {y}')


add(1, 2)
add('hello', 'world')

但在我的例子中,我想用如下关键字参数调用add:

add(x=1, y=2)
add(x='hello', y='world')

我还想将其与以下默认值一起使用:

from multipledispatch import dispatch


@dispatch(int, int)
def add(x=2, y=1):
    print(x + y)


@dispatch(str, str)
def add(x='hello', y='world'):
    print(f'{x} {y}')


add(x=1)
add(y='world')

尝试以这种方式使用时,dispatch decorator会忽略kwargs并引发以下异常:

Traceback (most recent call last):
  File "/home/tomer/.virtualenvs/sqa/lib/python3.8/site-packages/multipledispatch/dispatcher.py", line 269, in __call__
    func = self._cache[types]
KeyError: ()

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/tomer/windows-automation-testing/sqa/try.py", line 22, in <module>
    add(x=1, y=2)
  File "/home/tomer/.virtualenvs/sqa/lib/python3.8/site-packages/multipledispatch/dispatcher.py", line 273, in __call__
    raise NotImplementedError(
NotImplementedError: Could not find signature for add: <>

Tags: pyaddhellohomeworlddefcallfile
1条回答
网友
1楼 · 发布于 2024-06-18 08:41:35

当您看到NotImplementedError时,通常意味着您需要将其子类化并实现它。最常见的情况是,您有一些抽象类,它只是一个接口,您需要对其进行子类化并实现所需的方法

该方法有一个占位符,只需实现它即可

文件内容如下:Dispatches on all non-keyword arguments

相关问题 更多 >