如何更改其他函数的locals()结果?

2024-04-19 10:02:01 发布

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

我有这样的代码:

def f():
    i = 5
    g(locals())
    print 'in f:', i, j

def g(env):
    env['j'] = env['i'] + 1
    print 'in g:', env['i'], env['j']

f()

我得到:

in g: 5 6
in f: 5---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
NameError: global name 'j' is not defined

似乎g不能改变f中locals()所得到的局部变量。还有其他函数中的局部变量可以改变吗?你知道吗


Tags: 代码nameinenvmostdefcallglobal
1条回答
网友
1楼 · 发布于 2024-04-19 10:02:01

根据docs关于locals

Note The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.

另一种解决方案是只返回j。你知道吗

def f():
    i = 5
    j = g(locals())
    print 'in f:', i, j

def g(env):
    j = env['i'] + 1
    print 'in g:', env['i'], j
    return j

f()

相关问题 更多 >