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

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


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


当前回答

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

在本例中,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()

其他回答

您可能需要探索名称空间的概念。在Python中,模块是全局数据的自然位置:

每个模块都有自己的专用符号表,该表被模块中定义的所有函数用作全局符号表。因此,模块的作者可以在模块中使用全局变量,而不用担心与用户的全局变量发生意外冲突。另一方面,如果你知道你在做什么,你可以用与引用它的函数相同的符号modname.itemname来触摸模块的全局变量。

这里描述了模块中全局变量的具体用法-如何在模块之间共享全局变量?,为完整起见,内容如下:

在单个程序中跨模块共享信息的规范方法是创建一个特殊的配置模块(通常称为config或cfg)。只需在应用程序的所有模块中导入配置模块;然后,模块变为可用的全局名称。因为每个模块只有一个实例,所以对模块对象所做的任何更改都会在任何地方反映出来。例如:

文件:config.py

x=0#“x”配置设置的默认值

文件:mod.py

import config
config.x = 1

文件:main.py

import config
import mod
print config.x

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变量的。

类似此代码:

myVar = 12

def myFunc():
  myVar += 12

Key:

如果在字符串外部声明变量,它将变为全局变量。

如果在字符串中声明变量,它将变为本地变量。

如果要在字符串中声明全局变量,请在要声明的变量之前使用关键字global:

myVar = 124
def myFunc():
  global myVar2
  myVar2 = 100
myFunc()
print(myVar2)

然后文档中有100个。

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

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已更改