内置函数--global() 和 local()

时间:2022-07-25
本文章向大家介绍内置函数--global() 和 local(),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

 一 . globals :返回当前作用域内全局变量的字典。

>>> globals()
{'__spec__': None, '__package__': None, '__builtins__': <module 'builtins' (built-in)>, '__name__': '__main__', '__doc__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>}
>>> a = 1
>>> globals() #多了一个a
{'__spec__': None, '__package__': None, '__builtins__': <module 'builtins' (built-in)>, 'a': 1, '__name__': '__main__', '__doc__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>}

二 .local() 函数功能返回当前作用域内的局部变量和其值组成的字典,与globals函数类似(返回全局变量)

>>> locals()
{'__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__doc__': None, '__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>, '__spec__': None}

>>> a = 1

>>> locals() # 多了一个key为a值为1的项
{'__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, 'a': 1, '__doc__': None, '__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>, '__spec__': None}

  2. 可用于函数内。

>>> def f():
    print('before define a ')
    print(locals()) #作用域内无变量
    a = 1
    print('after define a')
    print(locals()) #作用域内有一个a变量,值为1

    
>>> f
<function f at 0x03D40588>
>>> f()
before define a 
{} 
after define a
{'a': 1}

  3. 返回的字典集合不能修改。

>>> def f():
    print('before define a ')
    print(locals()) # 作用域内无变量
    a = 1
    print('after define a')
    print(locals()) # 作用域内有一个a变量,值为1
    b = locals()
    print('b["a"]: ',b['a']) 
    b['a'] = 2 # 修改b['a']值
    print('change locals value')
    print('b["a"]: ',b['a'])
    print('a is ',a) # a的值未变

    
>>> f()
before define a 
{}
after define a
{'a': 1}
b["a"]:  1
change locals value
b["a"]:  2
a is  1
>>> 

总结: (老男孩python全栈视频教程)

global();获取全部的全局变量,返回一个字典

local():获取指定范围内的局部变量, 返回一个字典

def m():
    a = 10
    print("全局变量:", globals())
    print("局部变量:", locals())

m()

分析: 在m()函数内增加了一个a局部变量, 所以局部变量只有一个, 全局变量. 全局变量有很多, 都是默认的

  返回结果:

全局变量: {'__name__': '__main__', '__doc__': '内置函数', '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0291A410>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:/PycharmProjects/test/dir05/neiZhiHanShu.py', '__cached__': None, 'm': <function m at 0x02A53738>}

局部变量: {'a': 10}