python基础----1. globals和locals

官方文档

globals

"""
Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).
返回表示当前全局符号表的字典。这总是当前模块的字典(在函数或方法中,不是调用它的模块,而是定义它的模块)。
"""

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. Note that at the module level, locals() and globals() are the same dictionary.
更新并返回表示当前本地符号表的字典。 在函数代码块但不是类代码块中调用 locals() 时将返回自由变量。 请注意在模块层级上,locals() 和 globals() 是同一个字典。
"""
"""
When a name is used in a code block, it is resolved using the nearest enclosing scope. The set of all such scopes visible to a code block is called the block’s environment.
当一个名字在一个代码块中被使用时,将从最近的封闭作用域开始查找此名字……
"""
"""
If a name is bound in a block, it is a local variable of that block, unless declared as nonlocal. If a name is bound at the module level, it is a global variable. (The variables of the module code block are local and global.) If a variable is used in a code block but not defined there, it is a free variable.
如果一个名称被绑定在一个块中,那么它就是该块的一个局部变量,除非声明为非局部变量。如果名称在模块级绑定,则它是一个全局变量。(模块代码块的变量是局部变量和全局变量。)如果一个变量在一个代码块中使用,但没有在那里定义,那么它就是一个自由变量。
"""

举例说明

例1

var1 = 'at the top of module'
print('var1 in locals():', 'var1' in locals())    # 1
print('var1 in globals():', 'var1' in globals())    # 2

def func():
    var2 = 'in the scope of func'
    print('va2 in locals():', 'var2' in locals())    # 3
    print('va2 in globals():', 'var2' in globals())    # 4

func()

结果1

var1 in locals(): True
var1 in globals(): True
va2 in locals(): True
va2 in globals(): False
"""
结果说明:
1. 1和2都为True是因为在模块层级上,locals() 和 globals() 是同一个字典
2. 同1 3. var2为函数体内定义的局部变量,所以3为True,4为False
4. 同3
"""

例2

n = 100

def func():
    level, n = 'l1', 33
    print(locals())    # 1
    print('level' in globals())    # 2

    def outer():
        print(locals(), n)    # 3
        print(locals())    # 4
        print('level' in globals())    # 5
        print(globals()['n'])    # 6

    outer()

func()

 结果2

{'level': 'l1', 'n': 33}
False
{'n': 33} 33
{'n': 33}
False
100
"""
首先,在函数体外面只定义了一个全局变量,其余的全是局部变量。
1. 打印locals()时,会打印出函数体内定义的两个局部变量level和n
2. level为局部变量,所以2为False
3. 如果一个局部变量在一个代码中使用,但没有在那里定义,那它就是一个自由变量,自由变量会通过locals()返回,所以locals()中有n
4. outer函数本身没有定义局部变量,而函数内只使用了n这一局部变量,所以locals()也只返回n
5. 此模块只定义了一个全局变量,在模块顶部n=100,所以5为False,6为100
6. 同上
"""

注意:不管是locals()还是globals()的字典,其存储变量的名称时都是以字符串形式存储的。例如

a = 100
# globals()[a]    # 会报错
globals()['a']    # 会返回正确的值100

猜你喜欢

转载自www.cnblogs.com/miaoning/p/10752524.html