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

如何在Python函数中定义变量使其每次调用时不被重置?

Python函数调用保留变量值的实现方法

以下是4种常用的实现方案,可根据实际场景选择:

1. 函数属性实现(简单场景首选)

利用Python中函数本身是对象的特性,将状态保存在函数自定义属性中,仅第一次调用时初始化:

def test():
    # 仅首次调用初始化money属性
    if not hasattr(test, 'money'):
        test.money = 0
    x = input('')
    if x == "givemoney":
        test.money += 100
        print(test.money)
        test()
    else:
        print("something")

test()

2. 闭包实现

通过外层函数初始化状态变量,返回的内层函数可持有该变量的引用,每次调用不会重置:

def outer():
    money = 0
    def test():
        nonlocal money
        x = input('')
        if x == "givemoney":
            money += 100
            print(money)
            test()
        else:
            print("something")
    return test

test = outer()
test()

3. 全局变量实现(不推荐)

将状态变量定义在全局作用域,函数内通过global声明后修改,优点是实现简单,缺点是容易污染全局命名空间:

money = 0
def test():
    global money
    x = input('')
    if x == "givemoney":
        money += 100
        print(money)
        test()
    else:
        print("something")

test()

4. 类实现(复杂场景首选)

将状态和逻辑封装在类中,状态保存在实例属性里,可维护性和扩展性更强:

class MoneyCounter:
    def __init__(self):
        self.money = 0
    
    def test(self):
        x = input('')
        if x == "givemoney":
            self.money += 100
            print(self.money)
            self.test()
        else:
            print("something")

counter = MoneyCounter()
counter.test()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 01:06:04