Python动态地声明变量赋值

通过exec()、globals()和locals()

# 通过exec()
for i in range(1, 4):
    # 第一次循环 i=1 时,会执行字符串中的python语句 ex1 = "exec1",以此类推
    exec(f'ex{i} = "exec{i}"')

# 通过globals()和locals()
def test():
    # globals()
    for i in range(1, 4):
        # 第一次循环 i=1 时,执行 globals()['gb1'] = 'global1', globals()是一个dict
        globals()[f'gb{i}'] = f'global{i}'

    # locals()
    for i in range(1, 4):
        locals()[f'lc{i}'] = f'local{i}'

    # 尝试打印locals的变量
    try:
        print(lc1, lc2, lc3)    # 会报错
    except Exception as e:
        print(e)
        print(locals()['lc1'], locals()['lc2'], locals()['lc3'])    # 通过键值对

if __name__ == '__main__':
    # 执行
    test()
    print('---------------------')
    # 打印函数定义的全局变量
    print(gb1, gb2, gb3)
    print('---------------------')
    # 打印通过exec()定义的变量
    print(ex1, ex2, ex3)

输出结果:

name 'lc1' is not defined
local1 local2 local3
---------------------
global1 global2 global3
---------------------
exec1 exec2 exec3
上一篇:Python之路 1Day


下一篇:Python lambda表达式