import random
class Aa(object):
def __init__(self, ):
self.globalvars={}
#----------------------------------------------------------------------
def run(self,f):
for i in range(2):
f()
#----------------------------------------------------------------------
def saveGlobalVars(self,localsvar):
"""全局变量以 GVAR_开头"""
dict0={}
for k,v in localsvar.items():
if k.find('GVAR_')==0:
dict0[k]=v
self.globalvars=dict0
# print('self.dict0 have.......')
# print(self.globalvars)
class Bb(Aa):
def __init__(self, ):
super().__init__()
#----------------------------------------------------------------------
def callfun(self):
self.run(self.func)
#----------------------------------------------------------------------
def func(self):
if len(self.globalvars)>0: #将'全局'变量的值恢复
for k,v in self.globalvars.items():
locals()[k]=v
else:
GolN=10
for k in range(GolN): #全局变量
locals()['GVAR_'+ str(k)]=0
y=random.randint(0,9)
print('y=%d'%y)
if y<5:
locals()['GVAR_1']=y
print(locals())
print('GVAR_1=%d'%locals()['GVAR_1']) #我的困惑是,为什么 local()里面明明有 GVAR_1 这个变量,但是就是不能直接写成 print('GVAR_1=%d'%GVAR_1),有没有什么更好的办法?
self.saveGlobalVars(locals())
if name == "main": c=Bb() c.callfun()
1
chenstack 2018-03-21 11:44:21 +08:00
最小复现样例:
def test(): locals()['a'] = 1 print(locals()) print(a) python3 的文档是这样说的: 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. 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. 所以 function 中修改 locals()是没有意义的 |
2
dwjgwsm OP 你运行一下就知道了,确实可以修改啊
|