在dou local中定义的变量生成错误:变量。。。在声明之前引用

2024-09-29 23:19:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图理解Python中的名称空间。你知道吗

我尝试了Python文档中给出的这个场景。你知道吗

def scope_test():
    def do_local():
        spam = "local spam"
    def do_nonlocal():
        nonlocal spam
        spam = "nonlocal spam"
    def do_global():
        global spam
        spam = "global spam"
    do_local()
    print("before local assignment:", spam)
    do_nonlocal()
    print("before nonlocal assignment:", spam)
    do_global()
    print("before global assignment:", spam)

    spam = "test spam"

    do_local()
    print("After local assignment:", spam)
    do_nonlocal()
    print("After nonlocal assignment:", spam)
    do_global()
    print("After global assignment:", spam)

这不能说明:

The variable spam is referenced before its declared.

我已经在dou local()中清楚地定义了变量。你知道吗


Tags: 文档test名称localdef场景空间spam
1条回答
网友
1楼 · 发布于 2024-09-29 23:19:59

我从一个简单的例子开始:我尝试访问一个没有在任何地方定义的非局部变量。这将失败:

def scope_test1():

    # This function tries to access a non-local
    # variable spam. Since I never define spam,
    # this will cause an exception:
    # -> SyntaxError: no binding for nonlocal 'spam' found
    def do_nonlocal():
        nonlocal spam
        spam = "nonlocal spam"

这很容易解决:我只需在适当的范围内添加此变量:

def scope_test2():

    # This works:
    def do_nonlocal():
        nonlocal spam
        spam = "nonlocal spam"

    spam = "test spam"

现在我想添加一个本地版本的函数,让事情变得更有趣:

def scope_test3():

    # This function defines the variable spam, but
    # only locally, that is, it is not accesible from
    # outside
    def do_local():
        spam = "local spam"

    # The functions do_local() gets executed and
    # creates an internal variable spam. This variable
    # isn’t visible from the outside.
    do_local()

    # So far, the variable spam hasn’t been declared.
    # So this will fail:
    # -> UnboundLocalError: local variable 'spam' referenced before assignment
    print("after local assignment:", spam)

    # spam gets assigned here, but it’s too late
    spam = "test spam"

它再次失败:我稍后定义spam没有帮助(太晚了),而且do_local在本地分配给spam也没有帮助:函数scope_test3没有看到这个本地版本。你知道吗

我可能会尝试通过添加我的非本地版本来缓解这种情况:

def scope_test4():

    def do_local():
        spam = "local spam"

    # Accesses a nonlocal variable spam when it gets called,
    # but doesn't add it, so it can’t save us.
    def do_nonlocal():
        nonlocal spam
        spam = "nonlocal spam"

    do_local()

    # So far, the variable spam still hasn’t been declared.
    # So this will still fail:
    # -> UnboundLocalError: local variable 'spam' referenced before assignment
    print("after local assignment:", spam)

    # spam gets assigned here, but it’s still too late
    spam = "test spam"

但这也没什么帮助:do_nonlocal不会仅仅通过存在就神奇地将spam添加到它的非局部范围。你知道吗

相关问题 更多 >

    热门问题