首页 > 解决方案 > Python函数调用问题(一般)

问题描述

我必须根据标志变量以同步/异步方式调用我的更新聊天任务。我有这样的代码:

class UpdateChat:

    def __init__(self, is_async=True):
        self._async = is_async

    def update(self):
        parse_call = self._parse_async if self._async else self._parse_sync
        parse_call(utterance,dynamic_concepts,cache_id_str)
        # This should have ideally mapped correctly with function parameters of _parse_sync & _parse_async
        # But somehow: 
        #  - utterance is being mapped with dynamic_concepts
        #  - dynamic_concepts with  cache_id_str
        # cache_id_str not being mapped at all
     
     def _parse_sync(self, utterance, dynamic_concepts=None, cache_id_str=None):
        pass
        
      def _parse_async(self, utterance, dynamic_concepts=None, cache_id_str=None):
        pass

更新函数没有正确映射在 parse_call 中传递的参数(如上面的评论中所述)

两个问题,如果我可以:

标签: pythonpython-3.xfunctiondesign-patterns

解决方案


代码似乎按预期工作!

class UpdateChat:

    def __init__(self, is_async=True):
        self._async = is_async

    def update(self):
        utterance = "Hello"
        dynamic_concepts = "foo"
        cache_id_str = "bar"
        parse_call = self._parse_async if self._async else self._parse_sync
        parse_call(utterance,dynamic_concepts,cache_id_str)

    def _parse_sync(self, utterance, dynamic_concepts=None, cache_id_str=None):
        print(utterance, dynamic_concepts, cache_id_str)

    def _parse_async(self, utterance, dynamic_concepts=None, cache_id_str=None):
        pass

x = UpdateChat(False)
x.update()

输出:

Hello foo bar

映射一个函数是可以的。但是,您可以直接从 update(self) 调用 _parse_syn 和 _parse_async 方法。


推荐阅读