python - 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 中传递的参数(如上面的评论中所述)
两个问题,如果我可以:
- 为什么会这样?
- 这是实现这些功能的正确方法吗(从设计模式的角度来看?)我们应该使用接口(Python ABC)还是其他类似映射的东西?
解决方案
代码似乎按预期工作!
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 方法。
推荐阅读
- java - jnats 2.4.2 在关机时挂起
- java - 无法在浏览器上将 Spring Boot XSRF-TOKEN 标志设置为安全
- python - 最优列表理解(过滤现有列表)
- c# - 为什么不能使用静态只读对象属性?
- c# - 尝试用作 ContextFlyout 时,CommandBarFlyout 不断抛出 System.ArgumentException
- json - 自定义由 CL_SXML_STRING_WRITER 创建的 JSON
- c# - 如何从 Json 加载游戏对象?有可能吗?
- algolia - Algolia InstantSearch.js 的 searchFunction 参数不起作用
- ibm-doors - 可以为 DOORS 实数属性分配一个非限定值吗?
- apache-kafka - 可以在 apache kafka cluster kafka version 2.0.0 中安装 rest-proxy confluent