【发布时间】:2011-07-11 04:27:30
【问题描述】:
为什么变量 L 在sorting(L) 函数调用中被操纵?在其他语言中,L 的副本将作为副本传递给sorting(),这样对x 的任何更改都不会更改原始变量?
def sorting(x):
A = x #Passed by reference?
A.sort()
def testScope():
L = [5,4,3,2,1]
sorting(L) #Passed by reference?
return L
>>> print testScope()
>>> [1, 2, 3, 4, 5]
【问题讨论】:
-
我知道 sort() 会改变集合,但为什么它会改变 testScope() 中定义的原始 L。听起来 sort(L) 正在将 L 的引用传递给排序函数?正确的?这是一个正确的说法吗?
-
@lunixbochs:不,不,不!请停止暗示 Python、Java、C#(使用引用类型时)等语言使用 pass-by-reference。这是完全错误的。