Skip to main content
 首页 » 编程设计

python之为什么改变全局不会出错

2025年05月04日16soundcode

到底为什么 Python 允许更改而不是函数中的全局声明列表?

重新更新

numbers = [] 
num = 4 
 
def add(n, thisnum=None): 
    # changing global list without global declaration! 
    numbers.append(n) 
    if thisnum: 
         num = thisnum 
         print 'num assigned', thisnum 
    ##numbers = ('one', 'two', 'three') 
    ## adding this line makes error: 
"""Traceback (most recent call last): 
  File "J:\test\glob_vals.py", line 13, in <module> 
    add(i) 
  File "J:\test\glob_vals.py", line 6, in add 
    numbers.append(n) 
UnboundLocalError: local variable 'numbers' referenced before assignment 
""" 
 
for i in (1,2,3,564,234,23): 
    add(i) 
 
print numbers 
add(10, thisnum= 19) 
# no error 
print num 
# let the fun begin 
num = [4] 
add(10, num) 
print num 
 
# prints: 
"""[1, 2, 3, 56, 234, 23] 
num assigned 19 
4 
num assigned [4] 
[4] 
 
""" 

如果我将赋值给具有相同名称的变量,那么该行之前的操作将变为错误,而不是添加的行(我猜是字节码编译器发现了它)。

请您参考如下方法:

您不是在为全局变量赋值,而是在其上调用一个方法来更改其内容。这是允许的。

没有 global 关键字你不能做的是:

def add(n): 
    #global numbers 
    numbers = numbers + [n] 

结果:

Traceback (most recent call last): 
  File "C:\Users\Mark\Desktop\stackoverflow\python\test.py", line 8, in  
    add(i) 
  File "C:\Users\Mark\Desktop\stackoverflow\python\test.py", line 5, in add 
    numbers = numbers + [n] 
UnboundLocalError: local variable 'numbers' referenced before assignment 

The difference is that here I am not mutating the existing list - I'm trying to create a new list and reassign back to the global scope. But this cannot be done without the global keyword.


Regarding your update:

The following line is OK because it creates a new local name num in the scope of the function. This does not affect the value of the variable at the global scope.

num = thisnum