You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python嵌套函数中实现不重置计分板,如何输出1234而非0000?

解决三层嵌套计分板累加输出1234的问题

原代码每次调用game()时,都会重新初始化increasePlayerScore()里的scoreBoardPlayer和started变量,导致每次都是全新的闭包环境,状态无法跨game()调用保留,自然无法累加出1234。要解决这个问题,核心是让计分状态脱离每次game()调用的局部作用域,在多次调用间持续保留。

以下是几种可行的解决方案:

方案一:使用全局变量保存状态

将计分变量放到全局作用域,让所有闭包共享同一状态:

scoreBoardPlayer = 0
started = False

def game():
    def increasePlayerScore():
        def playerScoreIncrease():
            global scoreBoardPlayer, started   
            if started:
                scoreBoardPlayer += 1
            else: 
                started = True
                scoreBoardPlayer += 1  # 首次调用也需要累加,否则返回0
            return scoreBoardPlayer
        return playerScoreIncrease
    
    newPlayerScore = increasePlayerScore()
    print(newPlayerScore(), end='')
game()
game()
game()
game()

方案二:用函数属性存储状态(避免全局变量)

利用函数也是对象的特性,将状态绑定到game函数的属性上,既避免全局变量污染,又能保留状态:

def game():
    # 仅在首次调用game时初始化状态
    if not hasattr(game, 'scoreBoardPlayer'):
        game.scoreBoardPlayer = 0
        game.started = False

    def increasePlayerScore():
        def playerScoreIncrease():
            if game.started:
                game.scoreBoardPlayer += 1
            else: 
                game.started = True
                game.scoreBoardPlayer += 1
            return game.scoreBoardPlayer
        return playerScoreIncrease
    
    newPlayerScore = increasePlayerScore()
    print(newPlayerScore(), end='')
game()
game()
game()
game()

方案三:面向对象封装(更易维护)

如果允许调整代码结构,用类来封装计分状态会更清晰,扩展性更强:

class ScoreBoard:
    def __init__(self):
        self.score = 0
        self.started = False

    def increase(self):
        if self.started:
            self.score += 1
        else:
            self.started = True
            self.score += 1
        return self.score

def game():
    # 确保全局只有一个ScoreBoard实例
    if not hasattr(game, 'board'):
        game.board = ScoreBoard()
    print(game.board.increase(), end='')

game()
game()
game()
game()

以上三种方案都能让程序输出1234,可根据实际场景选择合适的实现方式。

内容的提问来源于stack exchange,提问作者Evan Sowards

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 11:07:08