如何避免代码中的If语句墙?多分支条件判断代码如何优化?
嘿,这个问题问得好!这种一长串的if-elif确实会让代码变得臃肿难维护——尤其是后续要加更多武器类型的时候,改起来特别麻烦,还容易漏写分支。下面给你几个Python里常用的优化方案,按需挑选就行:
方案1:字典映射(最常用的轻量方案)
如果每个分支只是简单的“输入值对应输出值”,用字典直接做映射是最简洁高效的。查找速度是O(1),比逐个判断的if-elif(O(n))快,而且增删改只需要修改字典,不用动逻辑代码。
示例代码:
# 先定义武器和角色的映射关系 weapon_to_role = { "sword": "Knight", "katana": "Samurai", "axe": "Viking" } # 使用时直接通过key取值,还能处理不存在的情况 weapon = "sword" role = weapon_to_role.get(weapon, "Unknown Warrior") # 第二个参数是默认值 print(role)
方案2:字典映射函数(适合逻辑复杂的场景)
如果每个分支不止是打印一句话,还有更多业务逻辑(比如计算伤害、调用其他方法),可以把函数作为字典的值,把每个分支的逻辑封装成独立函数,代码更模块化。
示例代码:
# 把每个角色的行为封装成独立函数 def handle_knight(): print("Knight draws sword and charges!") # 这里可以加更多逻辑:比如计算攻击伤害、播放动画等 def handle_samurai(): print("Samurai unsheathes katana in a flash!") def handle_viking(): print("Viking swings axe with brute force!") def handle_default(): print("Unknown warrior holds their weapon at the ready!") # 定义武器到函数的映射 weapon_handlers = { "sword": handle_knight, "katana": handle_samurai, "axe": handle_viking } # 使用时获取函数并调用 weapon = "katana" handler = weapon_handlers.get(weapon, handle_default) handler()
方案3:面向对象的策略模式(适合大型项目)
如果你的项目比较复杂,角色不仅有“动作”,还有更多属性和方法(比如生命值、防御值),那用策略模式+工厂模式会更合适,符合开闭原则——后续加新的武器和角色,只需要新增子类,不用修改原有代码。
示例代码:
# 定义抽象的战士基类 class Warrior: def __init__(self, weapon): self.weapon = weapon def perform_action(self): raise NotImplementedError("每个子类必须实现perform_action方法") # 具体的战士子类 class Knight(Warrior): def perform_action(self): print(f"Knight wielding {self.weapon} charges into battle!") class Samurai(Warrior): def perform_action(self): print(f"Samurai with {self.weapon} strikes with precision!") class Viking(Warrior): def perform_action(self): print(f"Viking swinging {self.weapon} crushes enemies!") # 工厂类:负责根据武器创建对应的战士对象 class WarriorFactory: _warrior_map = { "sword": Knight, "katana": Samurai, "axe": Viking } @classmethod def create_warrior(cls, weapon): warrior_class = cls._warrior_map.get(weapon) if warrior_class: return warrior_class(weapon) raise ValueError(f"没有对应武器{weapon}的战士类型") # 使用示例 weapon = "axe" try: warrior = WarriorFactory.create_warrior(weapon) warrior.perform_action() except ValueError as e: print(e)
总结一下
- 简单的键值映射:优先用字典直接映射值
- 每个分支有复杂逻辑:用字典映射函数
- 大型项目、需要扩展更多属性方法:用策略模式+工厂模式
内容的提问来源于stack exchange,提问作者MBee
相关产品推荐
相关产品推荐

