代码之家  ›  专栏  ›  技术社区  ›  Guy

如何将默认参数与multipledispatch一起使用?

  •  0
  • Guy  · 技术社区  · 7 年前

    我使用默认参数重载函数 multipledispatch (基于 this answer )

    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 项目

    self.function(ClassOne())
    

    我明白了

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

    但我想知道我是否能保持目前的结构。

    我该怎么修?

    0 回复  |  直到 7 年前
        1
  •  0
  •   QooBee    6 年前

    默认参数应该在@dispatch中声明为关键字参数,如果您想修改参数值,请记住在调用这些函数时传递关键字,而不是依赖position。

    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)
    
    
    推荐文章