不能直接通过`locals()在python中设置局部变量`

2024-04-25 19:08:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我会保持这个简短。为什么会出现以下行为?你知道吗

>>> globals()['x'] = 5
>>> x
5
>>> def f():
...    locals()['y'] = 7
...    y
...
>>> f()
Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    f()
  File "<pyshell#31>", line 3, in f
    y
NameError: name 'y' is not defined

下面是一个可以使用的示例:

import opcode
def foo():
    locals().update(opcode.opmap)
    #do stuff

Tags: inmostdeflinecallopcodefilelast

热门问题