函数中的 Python3 变量


def a():
    b = 1
    def x():
        b -= 1
    if something is something:
        x()
a()

我在这里想要的是将ba()更改为x()我试过使用;

def a():
    b = 1
    def x():
        global b
        b -= 1
    if something is something:
        x()
a()

但是,正如我所料,这告诉我全局b没有定义。

b在运行x()后需要更改,如果第二次调用x() b则需要x()将其设置为 - 0 而不是最初在 a() - 1 中设置的。

要更改在包含作用域中定义的变量的值,请使用 nonlocal 。 此关键字类似于 Intent to global(指示应将变量视为全局范围内的绑定(。

因此,请尝试以下操作:

def a():
    b = 1
    def x():
        # indicate we want to be modifying b from the containing scope
        nonlocal b
        b -= 1
    if something is something:
        x()
a()

这应该有效:

def a():
    b = 1
    def x(b):
        b -= 1
        return b
    b = x(b)
    return b
a()

最新更新