用字典键调用类方法替代if语句是否为不良编程实践?
问题:字典映射方法调用 vs if/elif,哪种更符合Python最佳实践?
我正在用Python开发一款终端UI游戏,用户需通过按键进行导航。我的Game类代码如下:
class Game(): def __init__(self, config='default', **kwargs): print('\n'*20) # self.game_settings = self.set_game_settings(config, kwargs) self.main_menu() def main_menu(self): '''Menu the player sees when playing the game''' print('Welcome to pyFastType!\n') print('Please dont use your mouse but only keyboard keys when prompt too to keep the window active or it wont detect your key presses afterwards.\nHave fun!\n\n') choice = self.propose_menu(question = 'Press the letter on the left to navigate through the menu:', choices = ['Play game', 'Leaderboard', 'Settings']) {0: self.confirm_game_settings_before_game(), 1: self.leaderboard(), 2: self.settings()}[choice] def propose_menu(self, question: str, choices: list) -> int: '''Print a new menu with question/answers with key pressed parameters ---------- question str: question to ask to the player choices list: list of choices for the user to answer returns ---------- Index of the list corresponding to the choice of the user ''' print(question.capitalize()) choices_first_letter = [] for choice in choices: print(f'\t{choice[0].upper()} - {choice}') choices_first_letter.append(choice[0].lower()) key = dk.next_key_pressed()[0].lower() return choices_first_letter.index(key)
在main_menu方法中,我通过字典键调用其他类方法,而非使用if语句。作为编程新手,我想知道是否应该改用if/elif语句,哪种方式更符合最佳实践、可读性更好?
回答
首先要指出你当前代码里的一个关键bug:你现在的字典写法会立即执行所有三个方法(confirm_game_settings_before_game、leaderboard、settings),不管用户选择了哪个选项——因为你在字典值里写的是带括号的方法调用(self.xxx()),这会在字典创建时就触发方法执行。正确的写法应该是把方法本身作为值,之后再调用:
# 修正后的写法 menu_actions = { 0: self.confirm_game_settings_before_game, 1: self.leaderboard, 2: self.settings } menu_actions[choice]()
接下来对比两种实现方式的优劣:
字典映射的优势
- 简洁性:当选项数量增多时,不用写一堆重复的
if/elif分支,代码更紧凑 - 可维护性:选项与对应方法的映射关系一目了然,新增或修改选项时,只需要调整字典内容,不用改动条件判断逻辑
- 扩展性:可以把映射关系单独抽离(比如作为类属性),甚至从配置文件加载,灵活度更高
if/elif的优势
- 直观性:对于编程新手来说,
if/elif的分支逻辑更直白,一眼就能看懂每个选择对应的操作 - 灵活性:如果后续某个选项需要添加额外逻辑(比如参数预处理、日志记录),
if/elif可以直接在分支里补充代码,不用调整映射结构
最佳实践建议
- 如果只是单纯根据索引调用对应方法,修正后的字典映射是更优雅的选择,符合Python"简洁胜于复杂"的设计哲学
- 建议把映射提前定义成变量(比如上面的
menu_actions),比直接写匿名字典可读性更好 - 如果后续每个选项需要添加差异化的额外操作,再考虑换成
if/elif也完全没问题——两种写法没有绝对的优劣,取决于你的需求场景
内容的提问来源于stack exchange,提问作者Marc
相关产品推荐
相关产品推荐

