我越来越意识到我的代码充满了 if/else 语句。x = 'this' if y > 0 else 'that'
最终,我开始写单行代码(例如:
由此
def increase_score(self, side)
if self.player.side == side:
self.enemy.score += 1
else:
self.player.score += 1
我会这样做
def increase_score(self, side)
# assume player.side is side
last_enemy_score = self.enemy.score
self.enemy.score += 1
# only change if player.side isn't side
if self.player.side != side:
self.enemy.score = last_enemy_score
self.player.score += 1
除了这两种方法之外,还有哪些有趣的替代方法可以替代逐行 if/else 语句?