使用这两个函数来查看全局和当地变量的字典。
locals()不包括通过global获取的变量。
globals()
locals()
函数内如果没有某个变量的赋值语句,函数内可以访问函数外的同名变量。
>>> import re
>>> a=0
>>> def sb():
print(re)
print(a+1)
return locals()
>>> sb()
<module 're' from 'G:\\360安全浏览器下载\\Python\\Python37-32\\lib\\re.py'>
1
{}
但如果函数内有某个变量的赋值语句,Python就会认为这是当地变量,可能会引发错误。
>>> def sb():
print(re)
print(a+1)
a=a+1
return locals()
>>> sb()
<module 're' from 'G:\\360安全浏览器下载\\Python\\Python37-32\\lib\\re.py'>
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
sb()
File "<pyshell#30>", line 3, in sb
print(a+1)
UnboundLocalError: local variable 'a' referenced before assignment
函数内可以定义重名函数(不改变外层函数)。
>>> def sb():
print(re)
print(a+1)
def sb():
a=a+1
return locals()
>>> sb()
<module 're' from 'G:\\360安全浏览器下载\\Python\\Python37-32\\lib\\re.py'>
1
{'sb': <function sb.<locals>.sb at 0x01E575D0>}
>>> sb()
<module 're' from 'G:\\360安全浏览器下载\\Python\\Python37-32\\lib\\re.py'>
1
{'sb': <function sb.<locals>.sb at 0x020C18A0>}
还可以使用global获取自己的函数名后再对函数本身重新定义。
>>> def sb():
print(re)
print(a+1)
global sb
def sb():
a=a+1
return locals()
>>> sb()
<module 're' from 'G:\\360安全浏览器下载\\Python\\Python37-32\\lib\\re.py'>
1
{}
>>> sb()
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
sb()
File "<pyshell#37>", line 6, in sb
a=a+1
UnboundLocalError: local variable 'a' referenced before assignment
定义同名函数或者为其赋值时,只从这两个地址里来回改变。
在两个定义函数语句中间访问的是上面那个函数,在两个定义函数语句上面和下面访问的是下面那个函数。
>>> for _ in [0]:
print(0,sb,sb())
def sb():
return False
print(1,sb,sb())
sb=1
print(2,sb)
def sb():
return True
print(3,sb,sb())
0 <function sb at 0x020C1858> True
1 <function sb at 0x020C1930> False
2 1
3 <function sb at 0x020C1930> True
>>> sb
<function sb at 0x020C1930>
>>> sb
<function sb at 0x020C1930>
>>> sb()
True
>>> def sb():
return True
>>> sb
<function sb at 0x020C1858>
>>> def sb():
return True
>>> sb
<function sb at 0x020C1930>
>>> def sb():
return True
>>> sb
<function sb at 0x020C1858>
>>> def sb():
return False
>>> sb
<function sb at 0x020C1930>
>>> def sb():
return False
>>> sb
<function sb at 0x020C1858>