Skip to main content
 首页 » 编程设计

python之重构python中的if语句

2025年05月04日16telwanggs

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

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)