s = [1, 2, 3]
t = s
t.reverse()
然后s和t都变成了[3, 2, 1]
但是如果s = [1, 2, 3]
t = s[::-1]
只有t是[3, 2, 1] s还是[1, 2, 3]不变的...
所以我比较奇怪,python中的赋值,什么时候是传值什么时候是传址?
<code class="language-python"><span class="o">>>></span> <span class="n">a</span> <span class="o">=</span> <span class="mi">1</span>
<span class="o">>>></span> <span class="n">b</span> <span class="o">=</span> <span class="mi">1</span>
<span class="o">>>></span> <span class="nb">id</span><span class="p">(</span><span class="n">a</span><span class="p">)</span> <span class="o">==</span> <span class="nb">id</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
<span class="bp">True</span>
<span class="o">>>></span> <span class="n">c</span> <span class="o">=</span> <span class="mi">1000000</span>
<span class="o">>>></span> <span class="n">d</span> <span class="o">=</span> <span class="mi">1000000</span>
<span class="o">>>></span> <span class="nb">id</span><span class="p">(</span><span class="n">c</span><span class="p">)</span> <span class="o">==</span> <span class="nb">id</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>
<span class="bp">False</span>
</code>
在python中, parameter sent to function 使用的全部是 by object。a=10
def function1(value):
value=20
print(value)
function1(a)
print(a)
结果是20
10
虽然传过去的是a这个object,但当function1对a赋值的时候,其实他并没有改变a,而是创建了一个新的object,这个object叫做value了。global当中的a并没有变。a=[10,11,12,13]
def function1(value):
value[1:3]=[]
print(value)
function1(a)
print(a)
结果是[10,13]
[10,13]