我仍然对如何在python中传递参数感到困惑。
我认为非原始类型是通过引用传递的,但是为什么下面的代码不能打印[1]呢?
def listTest(L):
L = L + [1]
def main:
l = []
listTest(l)
print l #prints []
以及如何使它起作用。
我想我需要通过引用传递“指向L的指针”
python大神给出的解决方案
在listTest()
中,您将L
重新绑定到新的list
对象; L + [1]
创建一个新对象,然后将其分配给L
。这样就保留了list
之前引用的原始L
对象。
您需要直接通过调用list
引用的方法来操纵L
对象,例如list.append()
:
def listTest(L):
L.append(1)
或者您可以使用list.extend()
:
def listTest(L):
L.extend([1])
或者您可以使用就地分配,这使可变类型有机会就地更改对象:
def listTest(L):
L += [1]