【问题标题】:Python: Change variable in function from a child/nested function? [duplicate]Python:从子/嵌套函数更改函数中的变量? [复制]
【发布时间】:2014-11-05 11:38:32
【问题描述】:

我有一个嵌套在另一个函数中的函数。我想从嵌套的函数中更改第一个函数中的变量。

def myfunc():
    step=0

    def increment():
        step+=1

    increment()
    increment()
    increment()
    print("Steps so far:", step)

myfunc()

给予

UnboundLocalError:赋值前引用了局部变量“step”

如果我尝试使用global,它也不会工作,因为它会尝试取消引用myfunc 之外不存在的变量step

有没有办法在没有全局变量的情况下做到这一点?

【问题讨论】:

    标签: python function namespaces global-variables


    【解决方案1】:

    step 声明为nonlocal 变量。它将使标识符引用封闭范围内的变量。

    def increment():
        nonlocal step
        step += 1
    

    注意仅限 Python 3.x。

    【讨论】:

    • @AshwiniChaudhary,你是对的。我相应地在答案中添加了注释。
    • 谢谢!第一次偶然发现非本地,它工作得很好?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-06
    • 1970-01-01
    • 1970-01-01
    • 2013-03-31
    • 2011-07-10
    • 2016-09-25
    相关资源
    最近更新 更多