dwjgwsm
V2EX  ›  问与答

把字符串变成变量的问题

  •  
  •   dwjgwsm · Mar 20, 2018 · 2249 views
    This topic created in 2977 days ago, the information mentioned may be changed or developed.

    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 replies    2018-03-21 11:59:09 +08:00
    chenstack
        1
    chenstack  
       Mar 21, 2018
    最小复现样例:
    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
       Mar 21, 2018
    你运行一下就知道了,确实可以修改啊
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4464 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 51ms · UTC 10:07 · PVG 18:07 · LAX 03:07 · JFK 06:07
    ♥ Do have faith in what you're doing.