python global关键字的用法详解
最近刚好有朋友遇到个global相关的问题,这里简单学习一下global关键字的用法。
想要更好的了解global关键字,首先要熟悉python的全局变量与局部变量的概念。global关键字的作用是可以申明一个局部变量为全局变量,下面看一下实例
一、变量作用域的说明
这里简单提一下变量作用域的概念,有兴趣的小伙伴,可以查一下相关的博客
1、局部变量
defa(): ##菊部变量-,- local=1 print(local) ##全局无法使用,只有自己可用 print(lobal)
2、全局变量
global_str='123' defa(): ##全菊变量-,- print(global_str) ##全菊变量大家都可以用 print(global_str)
3、内置作用域
系统内固定模块里定义的变量,如预定义在builtin模块内的变量。这里不介绍了。
4、嵌套作用域
用的也比较少,主要是用在闭包中,看栗子
defout(): ##函数内变量,但对于下级函数就是全局变量,对于外部来说就是局部变量 en=1 definside(): print(en) returnen returninside() out()
二、global关键字作用
1、在函数间global关键字的作用
defout(): ##global关键字作用 globalen en=1 ##调用other可以打印en,去掉global会报错。 other() print(out.__globals__) defother(): print(en) out()
2、在类中也是一样,不多说,怕越多越乱,类中可以用self。
3、其他文件导入,如果定义好了之后从其他文件导入了呢?会发生什么,看一下栗子,a文件仍为上面栗子中代码
fromreport.aimport* out() print(out.__globals__['en'])
结果:
1 1
还好还好,没有报错。
4、那么问题来了,如果要在另一个文件中继续定义函数,是不是也可以继续使用a文件中的global申明的全局变量呢?
fromreport.aimportout defb(): print(out.__globals__['en']) ##直接飙红了。-,- print(en) b()
果然报错了:
Traceback(mostrecentcalllast): File"/Users/dangfuli/Documents/PycharmProjects/asp/report/b.py",line9,inb() File"/Users/dangfuli/Documents/PycharmProjects/asp/report/b.py",line6,inb print(out.__globals__['en']) KeyError:'en'
也就是说,导入包的话,global定义的全局变量没有被加到globals里面。
5、上面好多地方都用到了,func.__globals__,这个运行一下,看个实例
defout(): ##global关键字作用 globalen en=1 other() print(out.__globals__) ##调用other可以打印en defother(): print(en) out() ##返回结果 {'__name__':'__main__','__doc__':None,'__package__':None,'__loader__':<_frozen_importlib_external.SourceFileLoaderobjectat0x10306a7b8>,'__spec__':None,'__annotations__':{},'__builtins__':,'__file__':'/Users/xxx/Documents/PycharmProjects/xxx/report/a.py','__cached__':None,'out': ,'other': ,'en':1}
可以看到,当前的函数用global之后,en变量就被加到了globals里面
下面看看导入到其他地方去的
#a.py defout(): ##global关键字作用 globalen en=1 other() print(out.__globals__['en']) ##调用other可以打印en defother(): print(en) #############上面是a文件,下面是b文件############# #b.py fromreport.aimportout defb(): ##globals里面没有en那个全局变量 out() print(b.__globals__['en']) b()
看一下结果:
1 Traceback(mostrecentcalllast): File"/Users/xxx/Documents/PycharmProjects/xxx/report/b.py",line8,inb() File"/Users/xxx/Documents/PycharmProjects/xxx/report/b.py",line6,inb print(b.__globals__['en']) KeyError:'en'
可以看到,导入的a文件正常运行,b文件打印en的时候就报错了。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。