我不知道是否有一个功能的属性 __dict__当该外部空间不是全局空间==模块时,的外部空间,当函数是嵌套函数时就是这种情况,在Python 3中
但是据我所知,在Python 2中没有这样的属性。
因此,做您想做的事的唯一可能性是:
1)使用别人所说的可变对象
2)
def A() :
b = 1
print 'b before B() ==', b
def B() :
b = 10
print 'b ==', b
return b
b = B()
print 'b after B() ==', b
A()
结果
b before B() == 1
b == 10
b after B() == 10
。
诺塔
CédricJulien的解决方案有一个缺点:
def A() :
global b # N1
b = 1
print ' b in function B before executing C() :', b
def B() :
global b # N2
print ' b in function B before assigning b = 2 :', b
b = 2
print ' b in function B after assigning b = 2 :', b
B()
print ' b in function A , after execution of B()', b
b = 450
print 'global b , before execution of A() :', b
A()
print 'global b , after execution of A() :', b
结果
global b , before execution of A() : 450
b in function B before executing B() : 1
b in function B before assigning b = 2 : 1
b in function B after assigning b = 2 : 2
b in function A , after execution of B() 2
global b , after execution of A() : 2
执行后的全局bA()已被修改,因此它可能不适用
只有在全局名称空间中存在带有标识符b的对象时,情况才如此