如何在多重调度中使用默认参数?

2024-01-02

我使用默认参数重载函数multipledispatch(基于这个答案 https://stackoverflow.com/a/29091980/5168011)

from multipledispatch import dispatch

class TestExampleTest(AbstractTest):
    @dispatch(ClassOne, bool, bool)
    def function(self, my_class, a=True, b=True):
        do_something()

    @dispatch(ClassTwo, bool)
    def function(self, my_class, a=True):
        do_something_else()

当我打电话时function()无需将值传递给bool item/s

self.function(ClassOne())

I get

NotImplementedError:找不到函数的签名

完整的堆栈跟踪:

ExampleTest.py:27 (TestExampleTest.test_example_test)
self = <ExampleTest.TestExampleTest object at 0x04326BB0>

    def test_example_test(self):
>       self.function(ClassOne())

ExampleTest.py:29: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <dispatched function>
args = (<ExampleTest.ClassOne object at 0x043262B0>,), kwargs = {}
types = (<class 'ExampleTest.ClassOne'>,), func = None

    def __call__(self, *args, **kwargs):
        types = tuple([type(arg) for arg in args])
        func = self.dispatch(*types)
        if not func:
            raise NotImplementedError('Could not find signature for %s: <%s>' %
>                                     (self.name, str_signature(types)))
E           NotImplementedError: Could not find signature for function: <ClassOne>

..\..\..\..\Automation\lib\site-packages\multipledispatch\dispatcher.py:434: NotImplementedError

注意:我知道我可以放弃@dispatch一起做一些类似的事情

def function(self, my_class_one=None, my_class_two=None, a=True, b=True):
    if my_class_one:
        do_something()
    elif my_class_two:
        do_something_else()

但我想知道是否可以保留当前的结构。

我该如何修复它?


默认参数应该在@dispatch中声明为关键字参数,然后如果你想在调用这些函数时修改具有默认值的参数值,请记住传递关键字而不是依靠位置。

from multipledispatch import dispatch

class TestExampleTest(AbstractTest):
    @dispatch(ClassOne, a=bool, b=bool)
    def function(self, my_class, a=True, b=True):  # 1st function
        do_something()

    @dispatch(ClassTwo, a=bool)
    def function(self, my_class, a=True):          # 2nd function
        do_something_else()


test_ins = TestExampleTest()

# call 1st function
test_ins.function(class_one_ins) 
test_ins.function(class_one_ins, a=False)
test_ins.function(class_one_ins, a=False, b=False)

# call 2nd function
test_ins.function(class_two_ins)
test_ins.function(class_two_ins, a=False)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在多重调度中使用默认参数? 的相关文章

随机推荐