如何在python中重置全局变量?

use*_*345 6 python django

SOME_VARIABLE = []

def some_fun:
    append in SOME_VARIABLE
    s = []
    s = SOME_VARIABLE
    SOME_VARIABLE = []  // Not setting to empty list.
    return s
Run Code Online (Sandbox Code Playgroud)

如何重置SOME_VARIABLE为空.

Rod*_*gue 9

如果您读取变量,Python会在整个范围链中查找它.这意味着:

GLOB_VAR = "Some string"

def some_fun():
    print GLOB_VAR
Run Code Online (Sandbox Code Playgroud)

将打印 Some string

现在,如果你写一个变量,Python会在本地范围内查找它,如果它找不到你在本地级别给出的名字的变量,那么它会创建一个.

这意味着在您的示例中,您已经为函数创建了一个名为SOME_VARIABLElocal 的变量some_fun,而不是更新全局变量SOME_VARIABLE.这是一个经典的python陷阱.

如果要写入全局,则必须明确告诉Python您正在讨论已存在的全局变量.为此,您需要使用global关键字.那么,以下内容:

GLOB_VAR = "Some string"

def some_fun():
    global GLOB_VAR
    GLOB_VAR = "Some other string"

some_fun()
print GLOB_VAR
Run Code Online (Sandbox Code Playgroud)

将打印Some other string.

注意:我认为这是一种鼓励人们将全局变量保持为只读的方式,或者至少考虑他们正在做的事情.

当您尝试先读取然后写入全局时,行为是相同的(只是更令人惊讶).下列:

GLOB_VAR = False

def some_fun():
    if GLOB_VAR:
        GLOB_VAR = False

some_fun()
Run Code Online (Sandbox Code Playgroud)

会提出:

Traceback (most recent call last):
  File "t.py", line 7, in <module>
    some_fun()
  File "t.py", line 4, in some_fun
    if GLOB_VAR:
UnboundLocalError: local variable 'GLOB_VAR' referenced before assignment
Run Code Online (Sandbox Code Playgroud)

因为我们将修改GLOB_VAR它,它被认为是一个局部变量.

更新:Ely Bendersky有一篇相关的深入帖子,对于更正式的细节值得阅读.


atz*_*tzz 6

您需要告诉解释器您正在谈论全局变量:

def some_fun:
    global SOME_VARIABLE
    ...
    SOME_VARIABLE = []
Run Code Online (Sandbox Code Playgroud)