Ton*_*nen 1 python global list side-effects
为什么在地球上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]
"""
Run Code Online (Sandbox Code Playgroud)
如果我将分配给具有相同名称的变量,则该行之前的操作将变为错误,而不是添加的行(字节代码编译器发现它,我猜).
您没有分配给全局变量,而是在其上调用一个更改其内容的方法.这是允许的.
没有global关键字你不能做的是:
def add(n):
#global numbers
numbers = numbers + [n]
Run Code Online (Sandbox Code Playgroud)
结果:
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
不同之处在于,我不是在改变现有列表 - 我正在尝试创建一个新列表并重新分配回全局范围.但是没有global关键字就无法做到这一点.
关于你的更新:
以下行是正常的,因为它num在函数范围内创建了一个新的本地名称.这不会影响全局范围内变量的值.
num = thisnum
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
456 次 |
| 最近记录: |