use*_*646 2939 python scope global-variables
如何在函数中创建或使用全局变量?
如果我在一个函数中创建一个全局变量,我如何在另一个函数中使用该全局变量?我是否需要将全局变量存储在需要访问的函数的局部变量中?
Pau*_*son 4059
您可以在其他函数中使用全局变量,方法是global
在分配给它的每个函数中将其声明为:
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
Run Code Online (Sandbox Code Playgroud)
我想它的原因是,由于全局变量是如此危险,Python希望通过明确要求global
关键字来确保你真正知道你正在玩的是什么.
如果要跨模块共享全局变量,请参阅其他答案.
Jef*_*non 741
如果我正确理解您的情况,您所看到的是Python处理本地(函数)和全局(模块)命名空间的结果.
假设你有一个这样的模块:
# sample.py
myGlobal = 5
def func1():
myGlobal = 42
def func2():
print myGlobal
func1()
func2()
Run Code Online (Sandbox Code Playgroud)
你可能希望这打印42,但它打印5.如前所述,如果你添加一个' global
'声明func1()
,那么func2()
将打印42.
def func1():
global myGlobal
myGlobal = 42
Run Code Online (Sandbox Code Playgroud)
这里发生的是Python假定在函数内的任何位置分配的任何名称都是该函数的本地名称,除非另有明确说明.如果它只是从名称读取,并且名称在本地不存在,它将尝试在任何包含范围中查找名称(例如模块的全局范围).
myGlobal
因此,当您为名称指定42时,Python会创建一个局部变量,该变量会隐藏同名的全局变量.那个本地超出范围并且在返回时被垃圾收集func1()
; 同时,func2()
除了(未修改的)全局名称之外,什么都看不到.请注意,此命名空间决策发生在编译时,而不是在运行时 - 如果您在分配myGlobal
内部func1()
之前读取内部值,则会得到一个UnboundLocalError
,因为Python已经确定它必须是局部变量但是它还没有与之相关的任何价值.但是通过使用' global
'语句,你告诉Python它应该在别处查找名称,而不是在本地分配它.
(我相信这种行为很大程度上是由于本地命名空间的优化 - 没有这种行为,每次在函数内部分配新名称时,Python的VM都需要执行至少三次名称查找(以确保名称没有' t已经存在于模块/内置级别),这将显着减慢非常常见的操作.)
gim*_*mel 206
您可能想要探索命名空间的概念.在Python中,模块是全局数据的自然场所:
每个模块都有自己的私有符号表,该表用作模块中定义的所有函数的全局符号表.因此,模块的作者可以在模块中使用全局变量,而不必担心与用户的全局变量的意外冲突.另一方面,如果您知道自己在做什么,则可以使用与其函数相同的符号来触摸模块的全局变量
modname.itemname
.
这里描述了模块中全局模块的特定用法 - 如何在模块间共享全局变量,并且为了完整性,内容在此处共享:
在单个程序中跨模块共享信息的规范方法是创建一个特殊的配置模块(通常称为config或cfg).只需在应用程序的所有模块中导入配置模块; 然后该模块可用作全局名称.因为每个模块只有一个实例,所以对模块对象所做的任何更改都会反映在任何地方.例如:
文件:config.py
x = 0 # Default value of the 'x' configuration setting
Run Code Online (Sandbox Code Playgroud)
文件:mod.py
import config
config.x = 1
Run Code Online (Sandbox Code Playgroud)
文件:main.py
import config
import mod
print config.x
Run Code Online (Sandbox Code Playgroud)
Sin*_*ion 86
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
>>>
Run Code Online (Sandbox Code Playgroud)
看看出现在作业左侧的baz foo()
是唯一的LOAD_FAST
变量.
J S*_*J S 57
如果要在函数中引用全局变量,可以使用global关键字声明哪些变量是全局变量.您不必在所有情况下都使用它(正如此处有人错误地声明的那样) - 如果表达式中引用的名称无法在定义此函数的函数的本地范围或范围中找到,则在全局范围内查找变量.
但是,如果分配给函数中未声明为全局的新变量,则它将隐式声明为local,并且它可以掩盖具有相同名称的任何现有全局变量.
此外,全局变量是有用的,与一些声称不同的OOP狂热者相反 - 特别是对于较小的脚本,其中OOP是过度的.
Rau*_*ets 43
除了已经存在的答案,并使这更令人困惑:
在Python中,仅在函数内引用的变量是隐式全局变量 .如果在函数体内的任何位置为变量分配了一个新值,则假定它是一个局部变量.如果在函数内部为变量赋予了新值,则该变量隐式为局部变量,您需要将其显式声明为"全局".
虽然起初有点令人惊讶,但片刻的考虑解释了这一点.一方面,要求指定变量的全局性可以防止意外的副作用.另一方面,如果所有全局引用都需要全局,那么您将始终使用全局.您必须将对内置函数或导入模块的组件的每个引用声明为全局.这种混乱会破坏全球声明识别副作用的有用性.
Aar*_*all 39
如果我在一个函数中创建一个全局变量,我该如何在另一个函数中使用该变量?
我们可以使用以下函数创建一个全局:
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'
Run Code Online (Sandbox Code Playgroud)
编写函数实际上并不运行其代码.所以我们称之为create_global_variable
函数:
>>> create_global_variable()
Run Code Online (Sandbox Code Playgroud)
您可以使用它,只要您不希望更改它指向的对象:
例如,
def use_global_variable():
return global_variable + '!!!'
Run Code Online (Sandbox Code Playgroud)
现在我们可以使用全局变量:
>>> use_global_variable()
'Foo!!!'
Run Code Online (Sandbox Code Playgroud)
要将全局变量指向其他对象,您需要再次使用global关键字:
def change_global_variable():
global global_variable
global_variable = 'Bar'
Run Code Online (Sandbox Code Playgroud)
请注意,在编写此函数后,实际更改它的代码仍未运行:
>>> use_global_variable()
'Foo!!!'
Run Code Online (Sandbox Code Playgroud)
所以在调用函数后:
>>> change_global_variable()
Run Code Online (Sandbox Code Playgroud)
我们可以看到全局变量已经改变.该global_variable
名称现在指向'Bar'
:
>>> use_global_variable()
'Bar!!!'
Run Code Online (Sandbox Code Playgroud)
请注意,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!!!'
Run Code Online (Sandbox Code Playgroud)
但使用该名称错误的局部变量不会更改全局变量:
>>> use_global_variable()
'Bar!!!'
Run Code Online (Sandbox Code Playgroud)
请注意,除非您确切地知道自己在做什么并且有充分的理由这样做,否则应该避免使用与全局变量具有相同名称的局部变量.我还没有遇到过这样的道理.
Boh*_*dan 32
使用并行执行时,如果您不了解发生的情况,全局变量可能会导致意外结果.以下是在多处理中使用全局变量的示例.我们可以清楚地看到每个进程都使用自己的变量副本:
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))
Run Code Online (Sandbox Code Playgroud)
输出:
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]
Run Code Online (Sandbox Code Playgroud)
小智 23
事实证明,答案总是很简单.
这是一个小样本模块,其中有一种简单的方法可以在main
定义中显示它:
def five(enterAnumber,sumation):
global helper
helper = enterAnumber + sumation
def isTheNumber():
return helper
Run Code Online (Sandbox Code Playgroud)
以下是如何在main
定义中显示它:
import TestPy
def main():
atest = TestPy
atest.five(5,8)
print(atest.isTheNumber())
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
这个简单的代码就像这样,它将执行.我希望它有所帮助.
gxy*_*xyd 22
你说的是使用这样的方法:
globvar = 5
def f():
var = globvar
print(var)
f() # Prints 5
Run Code Online (Sandbox Code Playgroud)
但更好的方法是使用这样的全局变量:
globavar = 5
def f():
global globvar
print(globvar)
f() #prints 5
Run Code Online (Sandbox Code Playgroud)
两者都给出相同的输出.
Moh*_*aka 21
您需要在要使用的每个函数中引用全局变量.
如下:
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]
"""
Run Code Online (Sandbox Code Playgroud)
Kyl*_*tan 19
实际上,您并未将全局存储在局部变量中,只是创建对原始全局引用所引用的同一对象的本地引用.请记住,Python中的所有内容都是指向对象的名称,并且在通常的操作中不会复制任何内容.
如果您不必明确指定标识符何时引用预定义的全局,那么您可能必须明确指定标识符何时是新的局部变量(例如,使用类似'var'命令的内容在JavaScript中看到).由于局部变量在任何严重且非平凡的系统中比全局变量更常见,因此Python的系统在大多数情况下更有意义.
您可以使用一种尝试猜测的语言,使用全局变量(如果存在)或创建局部变量(如果不存在).但是,这很容易出错.例如,导入另一个模块可能会无意中通过该名称引入全局变量,从而改变程序的行为.
Sag*_*hta 16
试试这个:
def x1():
global x
x = 6
def x2():
global x
x = x+1
print x
x = 5
x1()
x2() # output --> 7
Run Code Online (Sandbox Code Playgroud)
小智 13
接下来作为一个补充,使用一个文件来包含所有在本地声明的全局变量,然后'import as':
Stocksin = 300
Prices = []
Run Code Online (Sandbox Code Playgroud)
import initval as iv
def getmystocks():
iv.Stocksin = getstockcount()
def getmycharts():
for ic in range(iv.Stocksin):
Run Code Online (Sandbox Code Playgroud)
.....
Mar*_*oma 13
如果您有一个具有相同名称的局部变量,您可能希望使用该globals()
函数.
globals()['your_global_var'] = 42
Run Code Online (Sandbox Code Playgroud)
Mik*_*ton 12
写入全局数组的显式元素显然不需要全局声明,尽管写入"批发"确实有这样的要求:
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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
解释:
global_var
是一个全局变量,所有函数和类都可以访问该变量。
使用指向全局范围内写入的变量的func_1()
关键字来访问该全局变量。global
如果我没有写 global 关键字,那么global_var
里面的变量func_1
就被认为是局部变量,只能在函数内部使用。然后在内部func_1
,我将该全局变量增加了 1。
同样的情况也发生在func_2()
.
调用func_1
and后func_2
,你会看到global_var
已更改
有两种方法可以将变量声明为全局变量:
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()
Run Code Online (Sandbox Code Playgroud)
2. 在函数外部分配变量:
global_variable_2 = 2
Run Code Online (Sandbox Code Playgroud)
现在我们可以在其他函数中使用这些声明的全局变量:
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
Run Code Online (Sandbox Code Playgroud)
注1:
如果您想更改另一个函数内的全局变量,例如update_variables()
您应该在分配变量之前在该函数中使用 global 行:
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
Run Code Online (Sandbox Code Playgroud)
笔记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']
Run Code Online (Sandbox Code Playgroud)
小智 6
我正在添加这个,因为我没有在任何其他答案中看到它,它可能对某些类似的东西挣扎有用.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
Run Code Online (Sandbox Code Playgroud)
和
from pickle import dump
def dumpfile(name):
with open(name+".dat", "wb") as outfile:
dump(globals()[name], outfile)
return True
Run Code Online (Sandbox Code Playgroud)
只允许您将变量转储/加载到全局命名空间中.超级方便,没有麻烦,没有大惊小怪.很确定它只是python 3.
引用要在其中显示更改的类命名空间.
在此示例中,runner正在使用文件配置中的max.我希望我的测试在跑步者使用时改变max的值.
主/ config.py
max = 15000
Run Code Online (Sandbox Code Playgroud)
主/ runner.py
from main import config
def check_threads():
return max < thread_count
Run Code Online (Sandbox Code Playgroud)
测试/ 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()
Run Code Online (Sandbox Code Playgroud)
与不同平台/环境上的多处理相关的全局变量,一方面是 Windows/Mac OS,另一方面是 Linux。
我将通过一个简单的例子向你展示这一点,指出我前段时间遇到的一个问题。
如果您想了解为什么 Windows/MacOs 和 Linux 上的情况不同,您需要知道,启动新进程的默认机制......
它们在内存分配和初始化方面有所不同......(但我不在这里讨论)。
让我们来看看问题/例子......
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)
Run Code Online (Sandbox Code Playgroud)
如果你在 Windows 上运行它(我想也是在 MacOS 上),你会得到以下输出......
task 0: counter = 1
task 1: counter = 2
task 2: counter = 3
task 3: counter = 4
Run Code Online (Sandbox Code Playgroud)
如果你在 Linux 上运行它,你会得到以下内容。
task 0: counter = 1
task 1: counter = 1
task 2: counter = 1
task 3: counter = 1
Run Code Online (Sandbox Code Playgroud)
虽然这个问题已经得到解答,但我再次给出解决方案,因为我更喜欢单行这是如果您希望在函数内创建全局变量
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
Run Code Online (Sandbox Code Playgroud)