Python命名空间的本质:
一、命名空间的定义;
二、命名空间的查找顺序;
三、命名空间的生命周期;
四、通过locals()和globals() BIF访问命名空间。
重点是第四部分,我们将在此部分观察命名空间的内容。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: antcolonies
info = ‘Address:‘
def func_father(country):
def func_son(area):
city = ‘Shanghai‘ # 此处的city变量,覆盖了父函数的city变量
print(‘%s %s %s %s‘ %(info, country, city, area))
city = ‘Beijing‘
func_son(‘Changyang‘)
func_father(‘China‘)
执行结果为: Address: China Shanghai Changyang
以上示例中,info在全局命名空间中,country在父函数的命名空间中,city、area在自己函数的命名空间中。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: antcolonies
i = 1
def func2():
print(i)
i = i +1
# UnboundLocalError: local variable ‘i‘ referenced before assignment
# def func2():
# print(i) # 1
func2()
造成以上情况的的原因:当创建命名空间时,python会检查代码并填充局部命名空间。在python运行那行代码之前,就发现了对i的赋值(即i作为该命名空间的一员产生一个引用(覆盖了外层的引用)),并把它添加到局部命名空间中。当函数执行时,python解释器认为i在局部命名空间中但没有值,所以会产生错误。
def func3(): y=123 del y # 从命名空间中删除该变量名,引用也被删除 print(y) func3() #错误:UnboundLocalError: local variable ‘y‘ referenced before assignment #去掉"del y"语句后,运行正常
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: antcolonies
i = 1
def func3():
i = 123
del i
print(i)
func3()
# UnboundLocalError: local variable ‘i‘ referenced before assignment
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: antcolonies
def func_1(i, str):
x = 123
print(locals())
func_1(1, ‘first‘)
运行结果: {‘i‘: 1, ‘str‘: ‘first‘, ‘x‘: 123}
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: antcolonies ‘‘‘ create on 2017-4-7 by antcolonies ‘‘‘ import copy gstr = ‘global string‘ def func_1(i, info): x = 1234 print(locals()) func_1(1, ‘first‘) if __name__ == ‘__main__‘: print("the current scope‘s global varieties:\n%s" %str(globals())) ‘‘‘(运行结果) {‘info‘: ‘first‘, ‘i‘: 1, ‘x‘: 1234} the current scope‘s global varieties: {‘__loader__‘: <_frozen_importlib.SourceFileLoader object at 0x000000000279E828>, ‘__name__‘: ‘__main__‘, ‘gstr‘: ‘global string‘, ‘__doc__‘: ‘\ncreate on 2017-4-7\nby antcolonies\n‘, ‘__package__‘: None, ‘__spec__‘: None, ‘copy‘: <module ‘copy‘ from ‘D:\\Python\\lib\\copy.py‘>, ‘__cached__‘: None, ‘func_1‘: <function func_1 at 0x00000000020DCBF8>, ‘__builtins__‘: <module ‘builtins‘ (built-in)>, ‘__file__‘: ‘E:/python14_workspace/s14/day05/test/variety_1.py‘} ‘‘‘
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: antcolonies
def func1(i, info):
x = 12345
print(locals())
locals()["x"]= 6789
print("x=",x)
y=54321
func1(1 , "first")
globals()["y"]= 9876
print( "y=",y)
输出:
原文:http://www.cnblogs.com/ant-colonies/p/6679812.html