Python內建函數locals

高洛峰
發布: 2016-11-05 14:17:08
原創
1244 人瀏覽過

英文文件:

locals()

Update and return a dictionary representing the current local symbol table. Free variables are returned by locals()blonwhen it table. Free variables are returned by locals()blonwhen it it 片語 in function notmeat,not not f5555555555555p p.

說明:

  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
>>>
登入後複製

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板