#!/usr/bin/env python
class test:
def foo(arg):
x = 1
print locals()
foo(7)
foo('bar')
def getglobals():
if __name__ == "__main__":
z = 7
class test1:
def x():
print "1"
x()
def foo(arg):
x = 1
print locals()
locals()["x"] = 2
print "x =", x
print "z = ", z
globals()["z"] = 8
print "z = ", z
print locals()
foo(10)
class test:
def foo(arg):
x = 1
print locals()
foo(7)
foo('bar')
def getglobals():
if __name__ == "__main__":
for k, v in globals().items():
print k, "=", v
getglobals()z = 7
class test1:
def x():
print "1"
x()
def foo(arg):
x = 1
print locals()
locals()["x"] = 2
print "x =", x
print "z = ", z
globals()["z"] = 8
print "z = ", z
print locals()
foo(10)
globals 返回实际的全局名字空间,而不是一个拷贝:与 locals 的行为完全相反。所以对 globals 所返回的字典的任何的改动都会直接影响到全局变量。