Python——按值与按引用 [英] Python -- by value vs by reference
问题描述
直到最近,我还以为 Python 是按值传递参数的.例如,
def method1(n):n = 5返回 nn = 1m = 方法 1(n)>>>n == 5>>>错误的
但是如果我将一个列表传递给一个方法,比如
def method2(list):删除列表[0]返回列表list1 = [0,1,2,3,4,5]列表 2 = 方法 2(列表 1)>>>清单 1>>>[1,2,3,4,5]
它改变了列表.我又做了一个测试:
l1 = ['a','b','c','d']x = 方法 1(l1)>>>l1>>>['A B C D']
这里的列表没有改变.我的问题是
<块引用>为什么会发生这些不同的情况?
Python 总是 通过赋值传递 ,即使在第一种情况下,实际上传递的是对象引用.但是当您在函数内部进行赋值时,您会导致名称引用一个新对象.这不会改变用于将值传递给函数的名称/变量(在下面的示例中更好地解释).
示例 -
<预><代码>>>>定义函数(n):... n = [1,2,3,4]...返回 n...>>>l = [1,2,3]>>>功能(l)[1, 2, 3, 4]>>>升[1, 2, 3]<小时>
在您的情况下,当您执行 del list[0]
时,您实际上是在适当地改变 list
(从中删除第一个元素),因此它反映了在调用函数的地方也是如此.
Until recently, I thought Python passed parameters by value. For example,
def method1(n):
n = 5
return n
n = 1
m = method1(n)
>>> n == 5
>>> False
But if I pass in a list to a method, like
def method2(list):
del list[0]
return list
list1 = [0,1,2,3,4,5]
list2 = method2(list1)
>>> list1
>>> [1,2,3,4,5]
it mutates the list. I did another test:
l1 = ['a','b','c','d']
x = method1(l1)
>>> l1
>>> ['a','b','c','d']
Here the list did not change. My question is
Why do these different cases happen?
Python always passes by assignment , even in the first case, actually the object reference is passed. But when you do an assignment inside the function, you are causing the name to refer a new object. That would not mutate the name/variable that was used to pass the value to the function (Better explained in the below example).
Example -
>>> def func(n):
... n = [1,2,3,4]
... return n
...
>>> l = [1,2,3]
>>> func(l)
[1, 2, 3, 4]
>>> l
[1, 2, 3]
In your case, when you do del list[0]
you are actually mutating the list
in place (deleting the first element from it) , and hence it reflects in the place where the function was called from as well.
这篇关于Python——按值与按引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!