首页  >  文章  >  后端开发  >  Python内置函数locals

Python内置函数locals

高洛峰
高洛峰原创
2016-11-05 14:17:081246浏览

英文文档:

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()
{&#39;__package__&#39;: None, &#39;__loader__&#39;: <class &#39;_frozen_importlib.BuiltinImporter&#39;>, &#39;__doc__&#39;: None, &#39;__name__&#39;: &#39;__main__&#39;, &#39;__builtins__&#39;: <module &#39;builtins&#39; (built-in)>, &#39;__spec__&#39;: None}

>>> a = 1

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

  2. 可用于函数内。

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

    
>>> f
<function f at 0x03D40588>
>>> f()
before define a 
{} 
after define a
{&#39;a&#39;: 1}

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

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

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


声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn