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

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


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


您可能需要探索名称空间的概念。在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

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

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默认创建本地变量,并使用全局关键字显式选择其他行为。

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

如果要在函数中引用全局变量,可以使用global关键字声明哪些变量是全局变量。您不必在所有情况下都使用它(正如这里有人错误地宣称的那样)-如果表达式中引用的名称无法在定义该函数的函数的局部作用域中找到,则会在全局变量中查找该名称。

但是,如果您分配给函数中未声明为全局的新变量,则它将隐式声明为局部变量,并且它可能会覆盖同名的任何现有全局变量。

此外,全局变量是有用的,与一些OOP狂热者的说法相反——特别是对于较小的脚本,OOP是过度的。

如果我正确理解了您的情况,那么您看到的是Python如何处理本地(函数)和全局(模块)命名空间的结果。

假设你有这样一个模块:

# sample.py
_my_global = 5

def func1():
    _my_global = 42

def func2():
    print _my_global

func1()
func2()

您可能希望它打印42,但实际上它打印5。如上所述,如果向func1()添加一个“全局”声明,那么func2()将打印42。

def func1():
    global _my_global 
    _my_global = 42

这里发生的情况是,Python假设在函数中的任何地方,任何分配给的名称都是该函数的本地名称,除非另有明确说明。如果它只是从一个名称中读取,并且该名称在本地不存在,那么它将尝试在任何包含范围(例如模块的全局范围)中查找该名称。

因此,当将42指定给名称_my_global时,Python将创建一个局部变量,该变量将覆盖同名的全局变量。当func1()返回时,该local超出范围并被垃圾收集;同时,func2()只能看到(未修改的)全局名称。请注意,这个命名空间决定发生在编译时,而不是在运行时——如果在赋值之前读取func1()内部的_my_global值,则会得到UnboundLocalError,因为Python已经决定它必须是一个本地变量,但它还没有与之关联的任何值。但通过使用“global”语句,您告诉Python应该在其他地方查找名称,而不是在本地分配。

(我认为,这种行为主要源于对本地名称空间的优化——如果没有这种行为,Python的VM每次在函数内部分配新名称时都需要执行至少三次名称查找(以确保该名称在模块/内置级别上不存在),这将大大降低非常常见的操作速度。)

实际上,您并没有将全局变量存储在本地变量中,只是创建了对原始全局引用引用的同一对象的本地引用。请记住,Python中的几乎所有内容都是引用对象的名称,在通常的操作中不会复制任何内容。

如果您不必显式指定标识符何时引用预定义的全局变量,那么您可能必须显式指定何时标识符是新的局部变量(例如,使用JavaScript中的“var”命令)。由于在任何严肃和非平凡的系统中,局部变量比全局变量更常见,因此Python的系统在大多数情况下更有意义。

你可能有一种语言试图猜测,如果存在的话使用一个全局变量,如果不存在的话创建一个局部变量。然而,这很容易出错。例如,导入另一个模块可能会无意中引入一个同名的全局变量,从而改变程序的行为。

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

对于并行执行,如果您不了解正在发生的情况,全局变量可能会导致意外的结果。下面是在多处理中使用全局变量的示例。我们可以清楚地看到,每个过程都使用自己的变量副本:

import multiprocessing
import os
import random
import sys
import time

def worker(new_value):
    old_value = get_value()
    set_value(random.randint(1, 99))
    print('pid=[{pid}] '
          'old_value=[{old_value:2}] '
          'new_value=[{new_value:2}] '
          'get_value=[{get_value:2}]'.format(
          pid=str(os.getpid()),
          old_value=old_value,
          new_value=new_value,
          get_value=get_value()))

def get_value():
    global global_variable
    return global_variable

def set_value(new_value):
    global global_variable
    global_variable = new_value

global_variable = -1

print('before set_value(), get_value() = [%s]' % get_value())
set_value(new_value=-2)
print('after  set_value(), get_value() = [%s]' % get_value())

processPool = multiprocessing.Pool(processes=5)
processPool.map(func=worker, iterable=range(15))

输出:

before set_value(), get_value() = [-1]
after  set_value(), get_value() = [-2]
pid=[53970] old_value=[-2] new_value=[ 0] get_value=[23]
pid=[53971] old_value=[-2] new_value=[ 1] get_value=[42]
pid=[53970] old_value=[23] new_value=[ 4] get_value=[50]
pid=[53970] old_value=[50] new_value=[ 6] get_value=[14]
pid=[53971] old_value=[42] new_value=[ 5] get_value=[31]
pid=[53972] old_value=[-2] new_value=[ 2] get_value=[44]
pid=[53973] old_value=[-2] new_value=[ 3] get_value=[94]
pid=[53970] old_value=[14] new_value=[ 7] get_value=[21]
pid=[53971] old_value=[31] new_value=[ 8] get_value=[34]
pid=[53972] old_value=[44] new_value=[ 9] get_value=[59]
pid=[53973] old_value=[94] new_value=[10] get_value=[87]
pid=[53970] old_value=[21] new_value=[11] get_value=[21]
pid=[53971] old_value=[34] new_value=[12] get_value=[82]
pid=[53972] old_value=[59] new_value=[13] get_value=[ 4]
pid=[53973] old_value=[87] new_value=[14] get_value=[70]

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

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

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()

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

除了已经存在的答案之外,为了使这一问题更加令人困惑:

在Python中,仅在函数内部引用的变量是隐式全局。如果在任何地方为变量分配了新值在函数体中,假设它是局部的。如果变量如果在函数中分配了一个新值,则变量为隐式本地,您需要将其显式声明为“全局”。虽然一开始有点令人惊讶,但片刻的思考解释了这一方面,要求全局分配变量提供了防止意外的副作用。另一方面,如果全球对于所有全局引用都是必需的时间您必须将对内置函数或导入模块的组件。这种混乱会破坏全球宣言对识别副作用。

来源:Python中局部和全局变量的规则是什么?。

您的意思是使用以下方法:

globvar = 5

def f():
    var = globvar
    print(var)

f()  # Prints 5

但更好的方法是像这样使用全局变量:

globvar = 5
def f():
    global globvar
    print(globvar)
f()   #prints 5

两者的输出相同。

您需要在每个要使用的函数中引用全局变量。

如下:

var = "test"

def printGlobalText():
    global var #wWe are telling to explicitly use the global version
    var = "global from printGlobalText fun."
    print "var from printGlobalText: " + var

def printLocalText():
    #We are NOT telling to explicitly use the global version, so we are creating a local variable
    var = "local version from printLocalText fun"
    print "var from printLocalText: " + var

printGlobalText()
printLocalText()
"""
Output Result:
var from printGlobalText: global from printGlobalText fun.
var from printLocalText: local version from printLocalText
[Finished in 0.1s]
"""

试试看:

def x1():
    global x
    x += 1
    print('x1: ', x)

def x2():
    global x
    x = x+1
    print('x2: ', x)

x = 5
print('x:  ', x)
x1()
x2()

# Output:
# x:   5
# x1:  6
# x2:  7

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

文件initval.py:

Stocksin = 300
Prices = []

文件getstocks.py:

import initval as iv

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


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

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

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

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)。

写入全局数组的显式元素显然不需要全局声明,尽管“批发”写入它确实有这样的要求:

import numpy as np

hostValue = 3.14159
hostArray = np.array([2., 3.])
hostMatrix = np.array([[1.0, 0.0],[ 0.0, 1.0]])

def func1():
    global hostValue    # mandatory, else local.
    hostValue = 2.0

def func2():
    global hostValue    # mandatory, else UnboundLocalError.
    hostValue += 1.0

def func3():
    global hostArray    # mandatory, else local.
    hostArray = np.array([14., 15.])

def func4():            # no need for globals
    hostArray[0] = 123.4

def func5():            # no need for globals
    hostArray[1] += 1.0

def func6():            # no need for globals
    hostMatrix[1][1] = 12.

def func7():            # no need for globals
    hostMatrix[0][0] += 0.33

func1()
print "After func1(), hostValue = ", hostValue
func2()
print "After func2(), hostValue = ", hostValue
func3()
print "After func3(), hostArray = ", hostArray
func4()
print "After func4(), hostArray = ", hostArray
func5()
print "After func5(), hostArray = ", hostArray
func6()
print "After func6(), hostMatrix = \n", hostMatrix
func7()
print "After func7(), hostMatrix = \n", hostMatrix

如果您有一个同名的局部变量,您可能需要使用globals()函数。

globals()['your_global_var'] = 42

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

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

我补充了这一点,因为我在其他任何答案中都没有看到它,它可能对正在与类似问题作斗争的人有用。globals()函数返回一个可变的全局符号字典,您可以在其中“神奇地”使数据可用于代码的其余部分。例如:

from pickle import load
def loaditem(name):
    with open(r"C:\pickle\file\location"+"\{}.dat".format(name), "rb") as openfile:
        globals()[name] = load(openfile)
    return True

and

from pickle import dump
def dumpfile(name):
    with open(name+".dat", "wb") as outfile:
        dump(globals()[name], outfile)
    return True

将只允许您将变量转储/加载到全局命名空间中。超级方便,没有麻烦,没有麻烦。很确定它只是Python 3。

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

与不同平台/环境上的多处理相关的全局变量因为一边是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

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

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']

尽管这已经得到了回答,但我还是再次给出了解决方案,因为我更喜欢单线这是如果您希望在函数中创建全局变量

def someFunc():
    x=20
    globals()['y']=50
someFunc() # invoking function so that variable Y is created globally 
print(y) # output 50
print(x) #NameError: name 'x' is not defined as x was defined locally within function

类似此代码:

myVar = 12

def myFunc():
  myVar += 12

Key:

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

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

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

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

然后文档中有100个。

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

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!")

如果要访问全局变量,只需在函数中添加全局关键字前任:global_var=“是”

def someFunc():
   global global_var;
   print(nam_of_var)