Python之global

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

1Global

The global statement and its nonlocal cousin are the only things that are remotely like declaration statements in Python. They arenot type or size declarations; they arenamespace declarations. The global statement tells Python that a function plans to change one or more global names.

• Global names are variables assigned at the top level of the enclosing module file.

• Global names must be declared only if they are assigned within a function.

• Global names may be referenced within a function without being declared.

In otherWords, global allows us to change names that live outside a def at the top level of a module file.

2Example

The global statement consists of the keyword global, followed by one or more names separated by commas.

X = 88#Global Xdeffunc():globalX

X= 99#Global X: outside deffunc()PRint(X)#Prints 99

y, z = 1, 2#Global variables in moduledefall_global():globalx#Declare globals assignedx = y + z#No need to declare y, z: LEGB rule

x, y, and z are all globals inside the function all_global.y and z are global because they aren’t assigned in the function; x is global because it was listed in aglobal statement to map it to the module’s scope explicitly. Without the global here, x would be considered local by virtue of the assignment.

3accessglobals

#thismod.pyvar = 99#Global variable == module attributedeflocal():

var= 0#Change local vardefglob1():globalvar#Declare global (normal)var += 1#Change global vardefglob2():

var= 0#Change local varimportthismod#Import myselfthismod.var += 1#Change global vardefglob3():

var= 0#Change local varimportsys#Import system tableglob = sys.modules['thismod']#Get module object (or use __name__)glob.var += 1#Change global vardeftest():print(var)

local();print(var)

glob1();print(var)

glob2();print(var)

glob3()print(var)

run and get results

>>>importthismod>>>thismod.test()99

99

100

101

102

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航