gpt4 book ai didi

python - 重构python中的if语句

转载 作者:太空宇宙 更新时间:2023-11-04 08:05:32 25 4
gpt4 key购买 nike

我想和你一起咨询一段代码。我有:

if tuple_type == Operation.START_SERVER:
dictionary = ServersDictionary()
dictionary.start(some_param)
elif tuple_type == Operation.STOP_SERVER:
dictionary = ServersDictionary()
dictionary.stop(some_param)
(...)
elif tuple_type == Operation.START_APP:
dictionary = AppsDictionary()
dictionary.start(some_param)
elif ...
(....)

我有 27 个 if/elif。通常,我会进入 map - 函数调度程序,但在每个 if/elif 之后,我都有两行代码具有相同的 dictionary 引用。你能建议我一些干净的解决方案来替换那些丑陋的结构吗?

创建 27 个类来应用多态性或 27 个函数听起来不太好……你怎么看?

最佳答案

你说得对,映射是正确的选择。使用 getattr从名称访问方法:

mapping = {Operation.START_SERVER: (ServerDictionary, 'start', some_param),
Operation.STOP_SERVER: (ServerDictionary, 'stop', some_param),
Operation.START_APP: (AppsDictionary, 'start', some_param)}
...
cls, method, param = mapping[tuple_type]
dictionary = cls()
getattr(dictionary, method)(param)

关于python - 重构python中的if语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31936492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com