Use these two functions to view the dictionary of global and local variables .
locals() It does not include passing global Get the variable of .
globals()
locals()
If there is no assignment statement of a variable in the function , Variables with the same name outside the function can be accessed inside the function .
>>> import re
>>> a=0
>>> def sb():
print(re)
print(a+1)
return locals()
>>> sb()
<module 're' from 'G:\\360 Safe browser download \\Python\\Python37-32\\lib\\re.py'>
1
{
}
But if there is a variable assignment statement in the function ,Python It will be considered as a local variable , May cause errors .
>>> def sb():
print(re)
print(a+1)
a=a+1
return locals()
>>> sb()
<module 're' from 'G:\\360 Safe browser download \\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
Functions with duplicate names can be defined in functions ( Do not change the outer function ).
>>> def sb():
print(re)
print(a+1)
def sb():
a=a+1
return locals()
>>> sb()
<module 're' from 'G:\\360 Safe browser download \\Python\\Python37-32\\lib\\re.py'>
1
{
'sb': <function sb.<locals>.sb at 0x01E575D0>}
>>> sb()
<module 're' from 'G:\\360 Safe browser download \\Python\\Python37-32\\lib\\re.py'>
1
{
'sb': <function sb.<locals>.sb at 0x020C18A0>}
You can also use global Get your own function name and redefine the function itself .
>>> def sb():
print(re)
print(a+1)
global sb
def sb():
a=a+1
return locals()
>>> sb()
<module 're' from 'G:\\360 Safe browser download \\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
When defining or assigning a value to a function with the same name , Just change back and forth from these two addresses .
The function above is accessed in the middle of the two defining function statements , The following function is accessed above and below the two definition function statements .
>>> 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>