Python3 中的 locals() 内置方法返回全局命名空间中的变量 [英] locals() built-in method in Python3 returns the variable in the global namespace

查看:36
本文介绍了Python3 中的 locals() 内置方法返回全局命名空间中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

name = "Lenin Mishra"

def home():
    name = "Sonu"
    print(name)


home()
print(locals())

当我运行上述代码时,Python 返回一个包含变量名称的字典,其值为 Lenin Mishra.

When I run the above code, Python returns me a dictionary containing the variable name, which has a value of Lenin Mishra.

{'__name__': '__main__', '__doc__': '\nExperimenting with scope\n', '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x10323b400>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/Users/leninmishra/Desktop/python_basics/scope.py', '__cached__': None, 'name': 'Lenin Mishra', 'home': <function home at 0x101db5e18>}

但据我所知,被赋值为Lenin Mishra的变量名是在全局范围内.

But as far as I understand, the variable name which has been assigned the value of Lenin Mishra is in the global scope.

为什么会这样?

推荐答案

在你的代码中,locals()global 范围内执行,所以你得到了那个输出.

In your code, locals() executed at global scope, so you got that output.

如果您将 locals() 作为另一个函数的一部分执行,您可以获得该特定函数作用域的局部变量.

If you execute that locals() as part of another function, you could get the local variables to that specific function's scope.

例如,如果您编写如下代码,您可能会以空括号的形式输出.python 基于缩进工作.

For example, if you write your code as below, you could get out-put as empty brackets. python works based on indentation.

示例代码

def myfun():
    print(locals())

myfun()

输出

{}

示例代码 2

def home():
    name = "Sonu"
    print(locals())

home()

输出

{'name': 'Sonu'}

此示例 2 代码说明只有名称变量在其本地范围内可用.

This sample 2 code explains only name variable is available in its local scope.

帮助 locals 功能说明如下:

Help of locals function says as follows:

In [1]: ?locals
Signature: locals()
Docstring:
Return a dictionary containing the current scope's local variables.

NOTE: Whether or not updates to this dictionary will affect name lookups in
the local scope and vice-versa is *implementation dependent* and not
covered by any backwards compatibility guarantees.
Type:      builtin_function_or_method

这篇关于Python3 中的 locals() 内置方法返回全局命名空间中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆