当前位置: 移动技术网 > IT编程>脚本编程>Python > Python基于locals返回作用域字典

Python基于locals返回作用域字典

2020年10月17日  | 移动技术网IT编程  | 我要评论
英文文档:locals()update and return a dictionary representing the current local symbol table. free variab

英文文档:

locals()

update and return a dictionary representing the current local symbol table. free variables are returned by locals()when it is called in function blocks, but not in class blocks.

  返回当前作用域内的局部变量和其值组成的字典

说明:

  1. 函数功能返回当前作用域内的局部变量和其值组成的字典,与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
>>>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网