python locals () and globals () usage

1, locals () and globals () is a python's built-in functions, they provide a way to access the form dictionary of local variables and global variables.

def test(arg):
    a=1
    b=2
    data_dict = {}
    print locals()
    print globals()


if __name__ == '__main__':
    test(3)

Output:

{'data_dict': {}, 'b': 2, 'a': 1, 'arg': 3}
{'__name__': '__main__', '__doc__': '\nimport serial\nser = serial.Serial(\'COM1\',1152
00)\n#ser.setBaudrate(115200)\n#ser.setByteSize(8)\n#ser.setStopbits(1)\nprint (ser.por
tstr)\nresult=ser.write("\n".encode("gbk"))\nprint(result)\ndata = ser.readline(0)\n#da
ta = ser.read()\nprint (data)\n', '__package__': None, '__loader__': <_frozen_importlib
_external.SourceFileLoader object at 0x000000000296F0B8>, '__spec__': None, '__annotati
ons__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'test.py', '__c
ached__': None, 'str_to_int': <function str_to_int at 0x00000000004C1EA0>, 'test': <fun
ction test at 0x00000000029681E0>}

 

2, locals () Returns the current local variables deep copy, modify about locals () when the value of the variable, in fact, for the original variable itself is of no effect. The globals () returns a dictionary global variable, modify its contents, the value of real change. 

b = 5 # 定义一个全局变量
def test2():
    a=1
    locals()["a"] = 2  # 修改局部变量
    print "a=", a
    globals()["b"] = 6 # 修改全局变量
    print "b=", b

if __name__ == '__main__':
    test2()

Output:

a= 1
b= 6

3, used to dynamically define the locals :( dynamic output variable local variable)

count=[1,2]
for i in range(len(count)):	
	print(i)
	locals()['a'+str(i)]=[1,2,3]
	print(locals()['a'+str(i)])
	print('ss:%s'%a0)
	
print(a1)

Output:

0
[1, 2, 3]
ss:[1, 2, 3]
1
[1, 2, 3]
ss:[1, 2, 3]
[1, 2, 3]

 

Published 24 original articles · won praise 30 · views 50000 +

Guess you like

Origin blog.csdn.net/yufen9987/article/details/87792355