把字符串变成变量的问题

2018-03-20 23:01:16 +08:00
 dwjgwsm

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()

1462 次点击
所在节点    问与答
2 条回复
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()是没有意义的
dwjgwsm
2018-03-21 11:59:09 +08:00
你运行一下就知道了,确实可以修改啊

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/439895

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX