gpt4 book ai didi

python - Python 的 locals() 有什么作用?

转载 作者:行者123 更新时间:2023-11-28 19:10:36 24 4
gpt4 key购买 nike

Python 的 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. 当前本地符号表中到底有哪些内容?

  2. 在函数最开始调用locals()是否保证局部符号表与参数dict相同?

    例如,如果我们有以下程序:

    def foo(x, y):
    print(locals() == {'x': 1, 'y': 2})
    foo(1, 2)

    无论我们使用什么平台和 Python 实现,它总是输出 True 吗?

最佳答案

What are in the current local symbol table exactly?

嗯,你可以自己看看。在您的 Python 程序的最开始,locals() 返回的符号表如下所示:

print(locals())

哪些输出:

{'__doc__': None, '__spec__': None, '__package__': None, '__builtins__': 
<module 'builtins' (built-in)>, '__name__': '__main__', '__loader__':
<class '_frozen_importlib.BuiltinImporter'>,
'__file__': 'C:\\Users\\$Name$\\Desktop\\script.py'}

符号表由一些“魔法变量”和一些关于当前 Python 文件的信息组成。比如__file__键,里面包含了你当前源文件的名字。 locals 返回的内容的描述与符号表的定义非常匹配:

In computer science, a symbol table is a data structure used by a language translator such as a compiler or interpreter, where each identifier in a program's source code is associated with information relating to its declaration or appearance in the source. - Wikipedia: Symbol table

(强调我的)


Is the local symbol table guaranteed to be the same as the argument dict if locals() is called at the very beginning of a function?

答案是1。函数有自己的作用域。而且,正如名称所暗示的那样,locals() 仅返回当前范围的本地标识符。因此,在函数内部对 locals() 的调用不能被程序的外部范围更改。例如。

>>> var = 10 # global variable
>>> locals()['var'] # var is accessible in the current scope
10
>>> def func():
print(locals()['var']) # but not in this scope. Python will raise an error


>>> func()
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
func()
File "<pyshell#16>", line 2, in func
print(locals()['var'])
KeyError: 'var'
>>>

1<子>很难完全理解你在第二个问题中的要求,所以如果我的回答不相关,我深表歉意。但我相信你会问:如果我在函数的开头调用 locals(),在我的定义中,locals 返回的 dict() 是否保证保留一样吗?。如果不是这种情况,请更新您的问题,我会尝试重新回答。

关于python - Python 的 locals() 有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40796264/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com