如何在函数中创建或使用全局变量?

如何在其他函数中使用一个函数中定义的全局变量?


未能在适当的地方使用全局关键字通常会导致UnboundLocalError。在第一次使用后重新分配局部变量时,UnboundLocalError中解释了这方面的精确规则。一般来说,当寻求解释时,请将其他问题作为该问题的副本,当某人只需要知道全局关键字时,请关闭该问题。


当前回答

有两种方法可以将变量声明为全局变量:

1.在函数内部分配变量并使用全局线

def declare_a_global_variable():
    global global_variable_1
    global_variable_1 = 1

# Note to use the function to global variables
declare_a_global_variable() 

2.分配变量外部函数:

global_variable_2 = 2

现在我们可以在其他函数中使用这些声明的全局变量:

def declare_a_global_variable():
    global global_variable_1
    global_variable_1 = 1

# Note to use the function to global variables
declare_a_global_variable() 
global_variable_2 = 2

def print_variables():
    print(global_variable_1)
    print(global_variable_2)
print_variables() # prints 1 & 2

注1:

如果要更改另一个函数(如update_variables())中的全局变量,则应在分配变量之前在该函数中使用全局行:

global_variable_1 = 1
global_variable_2 = 2

def update_variables():
    global global_variable_1
    global_variable_1 = 11
    global_variable_2 = 12 # will update just locally for this function

update_variables()
print(global_variable_1) # prints 11
print(global_variable_2) # prints 2

注2:

在函数内部不使用全局行时,列表和字典变量的注释1有一个例外:

# declaring some global variables
variable = 'peter'
list_variable_1 = ['a','b']
list_variable_2 = ['c','d']

def update_global_variables():
    """without using global line"""
    variable = 'PETER' # won't update in global scope
    list_variable_1 = ['A','B'] # won't update in global scope
    list_variable_2[0] = 'C' # updated in global scope surprisingly this way
    list_variable_2[1] = 'D' # updated in global scope surprisingly this way

update_global_variables()

print('variable is: %s'%variable) # prints peter
print('list_variable_1 is: %s'%list_variable_1) # prints ['a', 'b']
print('list_variable_2 is: %s'%list_variable_2) # prints ['C', 'D']

其他回答

global_var = 10  # will be considered as a global variable


def func_1():
    global global_var  # access variable using variable keyword
    global_var += 1


def func_2():
    global global_var
    global_var *= 2
    print(f"func_2: {global_var}")


func_1()
func_2()
print("Global scope:", global_var) # will print 22

说明:

globalvar是一个全局变量,所有函数和类都可以访问该变量。

func_1()使用关键字global访问该全局变量,该关键字指向写入全局范围的变量。如果我没有写全局关键字,func_1内的变量global_var被认为是一个局部变量,只能在函数内使用。然后在func_1内,我将全局变量递增1。

在func_2()中也发生了同样的情况。

调用func_1和func_2后,您将看到global_var已更改

如果我在一个函数中创建一个全局变量,我如何在另一个函数上使用该变量?

我们可以使用以下函数创建全局:

def create_global_variable():
    global global_variable # must declare it to be a global first
    # modifications are thus reflected on the module's global scope
    global_variable = 'Foo' 

编写函数实际上不会运行其代码。因此我们调用create_global_variable函数:

>>> create_global_variable()

使用全局变量而不进行修改

只要您不希望更改它指向的对象,就可以使用它:

例如

def use_global_variable():
    return global_variable + '!!!'

现在我们可以使用全局变量:

>>> use_global_variable()
'Foo!!!'

从函数内部修改全局变量

要将全局变量指向其他对象,需要再次使用全局关键字:

def change_global_variable():
    global global_variable
    global_variable = 'Bar'

请注意,在编写此函数后,实际更改它的代码仍然没有运行:

>>> use_global_variable()
'Foo!!!'

因此,调用函数后:

>>> change_global_variable()

我们可以看到全局变量已经改变。global_variable名称现在指向“Bar”:

>>> use_global_variable()
'Bar!!!'

请注意,Python中的“全局”并不是真正的全局-它只是模块级的全局。因此,它只适用于在全局模块中编写的函数。函数会记住编写它们的模块,因此当它们导出到其他模块中时,它们仍然会查找创建它们的模块以查找全局变量。

同名的局部变量

如果创建同名的局部变量,它将覆盖全局变量:

def use_local_with_same_name_as_global():
    # bad name for a local variable, though.
    global_variable = 'Baz' 
    return global_variable + '!!!'

>>> use_local_with_same_name_as_global()
'Baz!!!'

但使用该错误命名的局部变量不会更改全局变量:

>>> use_global_variable()
'Bar!!!'

请注意,您应该避免使用与全局变量同名的局部变量,除非您确切地知道自己在做什么,并且有充分的理由这样做。我还没有遇到这样的原因。

我们在课堂上也有同样的行为

后续评论问道:

如果我想在类内的函数内创建一个全局变量,并想在另一个类内的另一个函数内使用该变量,该怎么办?

在这里,我演示了我们在方法中得到的行为与在正则函数中得到的相同:

class Foo:
    def foo(self):
        global global_variable
        global_variable = 'Foo'

class Bar:
    def bar(self):
        return global_variable + '!!!'

Foo().foo()

现在:

>>> Bar().bar()
'Foo!!!'

但我建议不要使用全局变量,而是使用类属性,以避免混淆模块名称空间。还要注意,我们这里不使用self参数-这些可以是类方法(如果从通常的cls参数中更改class属性,则很方便)或静态方法(没有self或cls)。

Python使用一个简单的启发式方法来决定应该从哪个范围加载变量,在本地和全局之间。如果变量名出现在赋值的左侧,但未声明为全局变量,则假定它是局部变量。如果它没有出现在赋值的左侧,则假定它是全局的。

>>> import dis
>>> def foo():
...     global bar
...     baz = 5
...     print bar
...     print baz
...     print quux
... 
>>> dis.disassemble(foo.func_code)
  3           0 LOAD_CONST               1 (5)
              3 STORE_FAST               0 (baz)

  4           6 LOAD_GLOBAL              0 (bar)
              9 PRINT_ITEM          
             10 PRINT_NEWLINE       

  5          11 LOAD_FAST                0 (baz)
             14 PRINT_ITEM          
             15 PRINT_NEWLINE       

  6          16 LOAD_GLOBAL              1 (quux)
             19 PRINT_ITEM          
             20 PRINT_NEWLINE       
             21 LOAD_CONST               0 (None)
             24 RETURN_VALUE        
>>> 

看看baz(出现在foo()赋值的左侧)是如何成为唯一的LOAD_FAST变量的。

引用要显示更改的类命名空间。

在本例中,runner使用文件config中的max。我希望我的测试在跑步者使用时更改max的值。

main/config.py

max = 15000

主/运行程序.py

from main import config
def check_threads():
    return max < thread_count 

测试/runner_test.py

from main import runner                # <----- 1. add file
from main.runner import check_threads
class RunnerTest(unittest):
   def test_threads(self):
       runner.max = 0                  # <----- 2. set global 
       check_threads()
Initialized = 0  #Here This Initialized is global variable  

def Initialize():
     print("Initialized!")
     Initialized = 1  #This is local variable and assigning 1 to local variable
while Initialized == 0:  

这里我们比较全局变量Initialized为0,因此当循环条件为true时

     Initialize()

函数将被调用。循环将是无限的

#if we do Initialized=1 then loop will terminate  

else:
    print("Lets do something else now!")