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

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


未能在适当的地方使用全局关键字通常会导致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']

其他回答

作为附加组件,使用一个文件来包含所有本地声明的全局变量,然后导入为:

文件initval.py:

Stocksin = 300
Prices = []

文件getstocks.py:

import initval as iv

def getmystocks(): 
    iv.Stocksin = getstockcount()


def getmycharts():
    for ic in range(iv.Stocksin):

您可以在其他函数中使用全局变量,方法是在为其赋值的每个函数中将其声明为全局变量:

globvar = 0

def set_globvar_to_one():
    global globvar    # Needed to modify global copy of globvar
    globvar = 1

def print_globvar():
    print(globvar)     # No need for global declaration to read value of globvar

set_globvar_to_one()
print_globvar()       # Prints 1

由于不清楚globvar=1是创建本地变量还是更改全局变量,Python默认创建本地变量,并使用全局关键字显式选择其他行为。

如果要在模块间共享全局变量,请参阅其他答案。

类似此代码:

myVar = 12

def myFunc():
  myVar += 12

Key:

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

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

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

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

然后文档中有100个。

全局变量很好-除了多处理

与不同平台/环境上的多处理相关的全局变量因为一边是Windows/Mac OS,另一边是Linux,这很麻烦。

我将用一个简单的例子向你展示这一点,指出我前段时间遇到的一个问题。

如果你想了解为什么Windows/MacOs和Linux上的情况不同需要知道的是,启动新进程的默认机制。。。

Windows/MacOs是“种子”Linux是“fork”

它们在内存分配和初始化方面有所不同。。。(但我不想谈这个此处)。

让我们看看这个问题/例子。。。

import multiprocessing

counter = 0

def do(task_id):
    global counter
    counter +=1
    print(f'task {task_id}: counter = {counter}')

if __name__ == '__main__':

    pool = multiprocessing.Pool(processes=4)
    task_ids = list(range(4))
    pool.map(do, task_ids)

窗户

如果你在Windows上运行这个(我想也是在MacOS上),你会得到以下输出。。。

task 0: counter = 1
task 1: counter = 2
task 2: counter = 3
task 3: counter = 4

Linux系统

如果您在Linux上运行此程序,则会得到以下结果。

task 0: counter = 1
task 1: counter = 1
task 2: counter = 1
task 3: counter = 1

事实证明,答案总是很简单。

下面是一个小示例模块,它以一种简单的方式在主定义中显示:

def five(enterAnumber,sumation):
    global helper
    helper  = enterAnumber + sumation

def isTheNumber():
    return helper

以下是如何在主要定义中显示它:

import TestPy

def main():
    atest  = TestPy
    atest.five(5,8)
    print(atest.isTheNumber())

if __name__ == '__main__':
    main()

这个简单的代码就是这样工作的,它会执行。我希望这有帮助。