可能重复:
了解Python的传递函数参数的逐个调用样式
我最近遇到过这个:
x = [1,2,3]
def change_1(x):
x = x.remove(x[0])
return x
Run Code Online (Sandbox Code Playgroud)
结果如下:
>>> change_1(x)
>>> x
[2, 3]
Run Code Online (Sandbox Code Playgroud)
我发现这种行为令人惊讶,因为我认为函数内部的任何内容都不会对外部变量产生影响.此外,我构建了一个示例,基本上做同样的事情,但没有使用remove:
x = [1,2,3]
def change_2(x):
x = x[1:]
return x
Run Code Online (Sandbox Code Playgroud)
结果如下:
>>> change_2(x)
[2, 3] # Also the output prints out here not sure why this is
>>> x
[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
我得到了我期望的结果,该函数不会改变x.
所以它必须是remove具有特定效果的东西.这里发生了什么?
其中一个令人困惑的事情是,你已经调用了很多不同的东西'x'.例如:
def change_1(x): # the x parameter is a reference to the global 'x' list
x = x.remove(x[0]) # on the left, though, is a new 'x' that is local to the function
return x # the local x is returned
>>> x = [1, 2, 3]
>>> y = change_1(x) # assign the return value to 'y'
>>> print y
None # this is None because x.remove() assigned None to the local 'x' inside the function
>>> print x
[2, 3] # but x.remove() modified the global x inside the function
def change_2(x):
x = x[1:] # again, x on left is local, it gets a copy of the slice, but the 'x' parameter is not changed
return x # return the slice (copy)
>>> x = [1, 2, 3]
>>> y = change_2(x)
>>> print x
[1, 2, 3] # the global 'x' is not changed!
>>> print y
[2, 3] # but the slice created in the function is assigned to 'y'
Run Code Online (Sandbox Code Playgroud)