【发布时间】:2011-05-24 00:05:40
【问题描述】:
为什么 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]
"""
如果我将赋值分配给具有相同名称的变量,那么 该行之前 的操作将变为错误,而不是添加的行(我猜是字节码编译器发现了它)。
【问题讨论】:
-
您似乎对范围规则感到困惑。在这方面有一些问题,质量答案遍布 SO,docs.python.org 也涵盖了这一点。
-
我仍然认为这不是一件微不足道的事情,或者从我自 1984 年以来作为教师和计算机科学专业学习的文档中显而易见。
-
我个人认为这很简单 - 可能比大多数语言中的范围规则更复杂,但仍然只有少数规则没有令人讨厌的例外。
-
感觉至少比 Ada 少很多痛苦,我们从中了解到 STRONG 类型意味着什么(幸运的是,Ada 编译器没有大型机时间来折磨我们,所以这只是理论上的)。
-
等等,什么?每种语言都有其规则,而 Ada 在其他所有领域肯定有更多规则。当你不知道规则时,你不能期望事情会顺利进行。
标签: python list global side-effects