简体   繁体   English

函数中的Python3变量

[英]Python3 variables in functions

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

What im wanting here is to change b from a() in x() I have tried using; 我在这里想要的是从我尝试使用的x() a()中更改b

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

a()

But this, as I expected, this told me global b is not defined. 但是,正如我所料,这告诉我全局b未定义。

b needs to change after x() is has run and if x() is called a second time b needs to be what x() set it to - 0 not what it was originally set to in a() - 1. b需要在运行x()后再次更改,并且如果第二次调用x()b必须是x()将其设置为-0的值,而不是a() -1中最初设置的值。

In order to alter the value of a variable defined in a containing scope, use nonlocal . 为了更改包含范围中定义的变量的值,请使用nonlocal This keyword is similar to intent to global (which indicates the variable should be considered to be the binding in the global scope). 此关键字类似于intent to global (这表示变量应被视为全局范围内的绑定)。

So try something like: 因此,尝试类似:

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()

This should work: 这应该工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM