Python 函数不改变全局变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12665994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Function not changing global variable
提问by cYn
my code is as follow:
我的代码如下:
done = False
def function():
for loop:
code
if not comply:
done = True #let's say that the code enters this if-statement
while done == False:
function()
For some reason when my code enters the if statement, it doesn't exit the while loop after it's done with function().
出于某种原因,当我的代码进入 if 语句时,它在使用 function() 完成后不会退出 while 循环。
BUT, if I code it like this:
但是,如果我这样编码:
done = False
while done == False:
for loop:
code
if not comply:
done = True #let's say that the code enters this if-statement
...it exits the while loop. What's going on here?
...它退出while循环。这里发生了什么?
I made sure that my code enters the if-statement. I haven't run the debugger yet because my code has a lot of loops (pretty big 2D array) and I gave up on debugging due to it being so tedious. How come "done" isn't being changed when it's in a function?
我确保我的代码进入了 if 语句。我还没有运行调试器,因为我的代码有很多循环(相当大的二维数组),我放弃了调试,因为它太乏味了。为什么“完成”在函数中没有改变?
采纳答案by Snakes and Coffee
Your issue is that functions create their own namespace, which means that donewithin the function is a different one than donein the second example. Use global doneto use the first doneinstead of creating a new one.
您的问题是函数创建了自己的命名空间,这意味着done函数内的命名空间done与第二个示例中的命名空间不同。使用global done使用第一done,而不是创建一个新的。
def function():
global done
for loop:
code
if not comply:
done = True
An explanation of how to use globalcan be found here
global可以在此处找到有关如何使用的说明
回答by Ionut Hulub
done=False
def function():
global done
for loop:
code
if not comply:
done = True
you need to use the global keyword to let the interpreter know that you refer to the global variable done, otherwise it's going to create a different one who can only be read in the function.
您需要使用 global 关键字让解释器知道您引用了全局变量done,否则它将创建一个只能在函数中读取的不同变量。
回答by Ashwini Chaudhary
Use global, only then you can modify a global variable otherwise a statement like done = Trueinside the function will declare a new local variable named done:
使用global,只有这样您才能修改全局变量,否则done = True函数内部的语句将声明一个名为 的新局部变量done:
done = False
def function():
global done
for loop:
code
if not comply:
done = True
Read more about the global statement.
阅读有关全球声明的更多信息。
回答by S3DEV
Using a classrather than global:
使用一个class而不是global:
Another way to handle (not use) global variables is to wrap the functions and variables you wish to be global in a class.
处理(不使用)全局变量的另一种方法是将您希望成为全局变量的函数和变量包装在一个类中。
While this is a little heavy for this specific case - classes add a host of functionality and flexability to the project. (Personally) highly recommended.
虽然这对于这个特定案例来说有点沉重 - 类为项目添加了许多功能和灵活性。(个人)强烈推荐。
For example:
例如:
class Processor():
"""Class container for processing stuff."""
_done = False
def function(self):
"""A function which processes stuff."""
# Some code here ...
self._done = True
# See the flag changing.
proc = Processor()
print('Processing complete:', proc._done)
proc.function()
print('Processing complete:', proc._done)
Output:
输出:
Processing complete: False
Processing complete: True

