【问题标题】:python method overloading - multipledispatch with kwargspython方法重载 - 使用kwargs的multipledispatch
【发布时间】:2021-01-14 09:47:38
【问题描述】:

我正在使用 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')

当尝试以这种方式使用它时,调度装饰器会忽略 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: <>

【问题讨论】:

    标签: python python-3.x python-3.8 keyword-argument multiple-dispatch


    【解决方案1】:

    当你看到 NotImplementedError 通常意味着你需要继承它并实现它。最常见的情况是你有一些抽象类,它只是一个接口,你需要子类化它并实现你需要的方法。

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

    文档阅读:Dispatches on all non-keyword arguments

    【讨论】:

    • 子类化什么并实现什么?你能举个例子让add(x=1, y=2)这个工作吗?
    猜你喜欢
    • 1970-01-01
    • 2015-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-29
    • 1970-01-01
    相关资源
    最近更新 更多