Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jsp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在函数中使用全局变量_Python_Global Variables_Scope - Fatal编程技术网

Python 在函数中使用全局变量

Python 在函数中使用全局变量,python,global-variables,scope,Python,Global Variables,Scope,如何在函数中创建或使用全局变量 如果在一个函数中创建全局变量,如何在另一个函数中使用该全局变量?我是否需要将全局变量存储在需要其访问的函数的局部变量中?您可能需要了解全局变量的概念。在Python中,是全局数据的自然场所: 每个模块都有自己的专用符号表,该表由模块中定义的所有函数用作全局符号表。因此,模块的作者可以在模块中使用全局变量,而不用担心与用户的全局变量发生意外冲突。另一方面,如果您知道自己在做什么,您可以使用用于引用其函数的相同符号modname.itemname来触摸模块的全局变量

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


如果在一个函数中创建全局变量,如何在另一个函数中使用该全局变量?我是否需要将全局变量存储在需要其访问的函数的局部变量中?

您可能需要了解全局变量的概念。在Python中,是全局数据的自然场所:

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

此处描述了global-in-A-module的具体用途,为完整起见,此处共享内容:

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

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
文件:config.py

文件:mod.py

文件:main.py


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

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
我认为这样做的原因是,由于全局变量非常危险,Python希望通过显式地要求使用global关键字来确保您真正知道这是您正在使用的


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

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

但是,如果在函数中为未声明为全局的新变量赋值,则该变量将隐式声明为局部变量,并且它可以覆盖任何具有相同名称的现有全局变量


此外,全局变量也很有用,与一些OOP狂热者声称的相反——特别是对于较小的脚本,OOP是一种过火的行为。

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

假设您有这样一个模块:

# sample.py
myGlobal = 5

def func1():
    myGlobal = 42

def func2():
    print myGlobal

func1()
func2()
globvar = 5

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

f()  # Prints 5
globvar = 5
def f():
    global globvar
    print(globvar)
f()   #prints 5
您可能希望它打印42,但它打印5。如前所述,如果向func1添加“全局”声明,则func2将打印42

def func1():
    global myGlobal
    myGlobal = 42
这里发生的事情是,Python假定在函数中的任何位置分配给的任何名称都是该函数的本地名称,除非明确地告知其他名称。如果它只读取一个名称,而该名称在本地不存在,它将尝试在任何包含范围(例如模块的全局范围)中查找该名称

因此,当您将42赋给名称myGlobal时,Python会创建一个局部变量,该局部变量会隐藏同名的全局变量。当func1返回时,该局部超出范围;同时,func2只能看到未修改的全局名称。请注意,此名称空间决策发生在编译时,而不是在运行时-如果要在赋值之前读取func1中的myGlobal值,则会出现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        
>>> 

请参见foo中赋值左侧的baz是如何成为唯一的LOAD\U 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))
>>> use_global_variable()
'Foo!!!'
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!!!'
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
输出:


事实证明,答案总是简单的

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

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()
以下是如何在主定义中显示它:

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中,只在函数中引用的变量是 隐式全局。如果在任意位置为变量指定了新值 在函数体中,它被假定为局部函数。如果一个变量 如果在函数中指定了新值,则变量为 隐式本地,并且您需要显式地将其声明为“全局”

虽然一开始有点令人惊讶,但考虑一下就可以解释 这一方面,为指定的变量要求全局变量提供了 防止意外的副作用。另一方面,如果全球 对于所有全局引用都是必需的,您将在所有 时间您必须将对内置函数的每个引用都声明为全局引用 函数或导入模块的组件。这种杂乱无章的东西 挫败《全球宣言》在确定 副作用


来源:。

你所说的是使用这样的方法:

# sample.py
myGlobal = 5

def func1():
    myGlobal = 42

def func2():
    print myGlobal

func1()
func2()
globvar = 5

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

f()  # Prints 5
globvar = 5
def f():
    global globvar
    print(globvar)
f()   #prints 5
但更好的方法是像这样使用全局变量:

# sample.py
myGlobal = 5

def func1():
    myGlobal = 42

def func2():
    print myGlobal

func1()
func2()
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: 全球x x+=1 打印'x1:',x def x2: 全球x x=x+1 打印'x2:',x x=5 打印'x:',x x1 x2 输出: x:5 x1:6 x2:7
作为附加组件,使用一个文件包含所有本地声明的全局变量,然后导入为:

文件initval.py:

文件getstocks.py:

如果在一个函数中创建全局变量,如何在另一个函数中使用该变量? 我们可以使用以下函数创建一个全局函数:

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()
>>> change_global_variable()
# 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']
编写函数实际上并不运行其代码。所以我们称之为create_global_variable函数:

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()
>>> change_global_variable()
# 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']
不加修改地使用globals 您可以直接使用它,只要您不希望更改它指向的对象:

比如说,

def use_global_variable():
    return global_variable + '!!!'
现在我们可以使用全局变量:

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))
>>> use_global_variable()
'Foo!!!'
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!!!'
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
从函数内部修改全局变量 要将全局变量指向其他对象,需要再次使用全局关键字:

def change_global_variable():
    global global_variable
    global_variable = 'Bar'
请注意,在编写此函数后,实际更改它的代码仍然没有运行:

>>> use_global_variable()
'Foo!!!'
因此,在调用函数之后:

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()
>>> change_global_variable()
# 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']
我们可以看到全局变量已经更改。全局变量名现在指向“Bar”:

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

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

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))
>>> use_global_variable()
'Foo!!!'
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!!!'
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
但使用该命名错误的局部变量不会更改全局变量:

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))
>>> use_global_variable()
'Foo!!!'
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!!!'
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
请注意,您应该避免使用与全局变量同名的局部变量,除非您确切知道自己在做什么,并且有很好的理由这样做。我还没有遇到这样的理由

我们在课堂上也有同样的行为 下面的评论是:

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

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

Foo类: def fooself: 全局变量 全局变量='Foo' 分类栏: def barself: 返回全局_变量+'!!!' Foo.Foo 现在:

>>>酒吧 “福!!!”
但是我建议不要使用全局变量,而是使用类属性,以避免模块名称空间混乱。另外请注意,我们这里不使用自参数-如果将class属性从通常的cls参数或静态方法(无自参数或cls)更改为class属性,则这些方法可能非常方便。

写入全局数组的显式元素显然不需要全局声明,尽管批量写入它确实有此要求:

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

如果您有一个同名的局部变量,您可能需要使用


引用要在其中显示更改的类命名空间

在本例中,runner使用文件配置中的max。我希望我的测试在runner使用时更改max的值

main/config.py

main/runner.py

测试/跑步者测试.py


我添加这一点,因为我在其他任何答案中都没有看到过,它可能对正在与类似问题作斗争的人有用。该函数返回一个可变的全局符号字典,您可以在其中神奇地为代码的其余部分提供数据。 例如:

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

只允许您将变量从全局命名空间中转储/加载到全局命名空间中。超级方便,没有混乱,没有大惊小怪。可以肯定的是,它只是Python3。

Globals很好——除了多处理之外 与不同平台/环境上的多处理相关的全局 因为Windows/Mac操作系统和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 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
现在我们可以在其他函数中使用这些声明的全局变量:

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)中更改全局变量,则应在分配变量之前在该函数中使用全局行:

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))
>>> use_global_variable()
'Foo!!!'
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!!!'
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中的列表和字典变量有一个例外,但在函数中不使用全局行:

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

把全球人说成如此危险是极端夸张的。在所有曾经存在和将要存在的语言中,Globals都是完美的。他们有自己的位置。你应该说的是,如果你不知道如何编程,它们可能会引起问题。我认为它们相当危险。然而,在python中,全局变量实际上是模块级的,这解决了很多问题。谢谢,我对python是新手,但对java略知一二。你说的对我有用。在课堂上写一篇全局a。。对我来说似乎比在函数中写“全局a”更有意义。。我注意到你不能说全局a=4这对我来说可能是最简单但非常有用的python技巧。我将这个模块命名为global_vars,并初始化init_global_vars中的数据,该数据在启动脚本中被调用。然后,我只需为每个定义的全局变量创建访问器方法。我希望我可以多次向上投票!谢谢你,彼得!如果有许多全局变量,我不想在全局语句后逐个列出它们,该怎么办?“在每个要使用的函数中”是不正确的,应该更接近:“在每个要更新的函数中”启发式搜索绑定操作。分配就是这样一个操作,导入另一个操作。但是for循环的目标和as-in-with和except语句后面的名称也绑定到了@MartijnPieters-in-as-in-except子句后面的名称对我来说并不明显。但是它被自动删除是为了保存内存。@Robert:不是为了保存内存,而是为了避免创建循环引用,循环引用可能导致内存泄漏。这是因为异常引用了回溯,而回溯引用了整个调用堆栈中的每个本地和全局命名空间,包括as。。。您提到名称空间决策发生在编译时,我认为这不是真的。根据我所了解的python编译,如果需要,请尝试以下示例defa:x+=1
不要运行它,它不会给出UnboundLocalError,请验证谢谢对全局变量使用大写字母是很常见的,例如MyGlobal=5@watashiSHUN:命名空间决策在编译时发生。确定x是本地的不同于在运行时检查本地名称是否在第一次使用之前绑定到某个值。@Vassilis:大写字母都是通用的:MY_GLOBAL=5。请参阅。将全局变量移动到另一个文件有什么好处?是否只是将全局变量组合在一个小文件中?为什么要使用语句导入。。。像为什么不直接进口…?啊。。。我终于明白了它的好处:不需要使用关键字global:-=>+1:-请编辑您的答案,以澄清其他人可能也有的疑问。干杯我不喜欢config.x的原因我能把它扔掉吗?我附带了x=lambda:config.x,然后在x中有了新值。出于某种原因,拥有a=config.x对我来说并不奏效。@vladosaurus从config import x解决了这个问题吗?@vladosaurus从config import xglobals使用总是返回本地上下文中可用的全局变量,因此这里的变异可能不会反映在另一个模块中。绝对是。狂热分子。大多数Python用户使用它编写脚本,并创建一些小函数来分离一些小代码。很酷,但是如果我想在一个类中的一个函数中创建一个全局变量,并且想在另一个类中的另一个函数中使用该变量,该怎么办?有点卡住了here@anonmanx我不知道你为什么会被卡住,这和在常规函数中的行为是一样的。但我会用你的评论和一些演示代码更新我的答案,好吗?好的,明白了。因此,我必须显式调用该函数才能使用该全局变量。第二个示例给出了NameError:名称“globvar”未在Python3.7Pim中定义:现在应该可以工作了,修复了输入错误:s/globavar/globvar/恭喜!终于有人明白了最重要的一点,那就是使用global。即在函数中使用在函数本身之后定义的变量。