V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
dwjgwsm
V2EX  ›  问与答

把字符串变成变量的问题

  •  
  •   dwjgwsm · 2018-03-20 23:01:16 +08:00 · 1448 次点击
    这是一个创建于 2236 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    2 条回复    2018-03-21 11:59:09 +08:00
    chenstack
        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()是没有意义的
    dwjgwsm
        2
    dwjgwsm  
    OP
       2018-03-21 11:59:09 +08:00
    你运行一下就知道了,确实可以修改啊
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1236 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 17:25 · PVG 01:25 · LAX 10:25 · JFK 13:25
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.