This question already has answers here:
Understanding Python's call-by-object style of passing function arguments
(3个答案)
可能重复:
Understanding Python's call-by-object style of passing function arguments
我最近发现:
结果是:
我发现这种行为令人惊讶,因为我认为函数内部的任何东西对外部变量都没有影响此外,我构建了一个示例,其中基本上做了相同的事情,但没有使用
结果是:
我得到了我期望的结果,函数不会改变x。
所以一定是某些特定的东西起作用这是怎么回事?
(3个答案)
可能重复:
Understanding Python's call-by-object style of passing function arguments
我最近发现:
x = [1,2,3]
def change_1(x):
x = x.remove(x[0])
return x
结果是:
>>> change_1(x)
>>> x
[2, 3]
我发现这种行为令人惊讶,因为我认为函数内部的任何东西对外部变量都没有影响此外,我构建了一个示例,其中基本上做了相同的事情,但没有使用
remove
:x = [1,2,3]
def change_2(x):
x = x[1:]
return x
结果是:
>>> change_2(x)
[2, 3] # Also the output prints out here not sure why this is
>>> x
[1, 2, 3]
我得到了我期望的结果,函数不会改变x。
所以一定是某些特定的东西起作用这是怎么回事?
最佳答案
令人困惑的一件事是,你把很多不同的东西叫做“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'