Rumah > pembangunan bahagian belakang > Tutorial Python > Python内置函数locals

Python内置函数locals

高洛峰
Lepaskan: 2016-11-05 14:17:08
asal
1258 orang telah melayarinya

英文文档:

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}
Salin selepas log masuk

  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}
Salin selepas log masuk

 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
>>>
Salin selepas log masuk


Label berkaitan:
sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan