當你創建一個對象并給它賦一個變量的時候,這個變量僅僅 引用 那個對象,而不是表示這個
對象本身!也就是說,變量名指向你計算機中存儲那個對象的內存。這被稱作名稱到對象的綁
定。
#!/usr/bin/python
# Filename: reference.py
print 'Simple Assignment'
shoplist = ['apple', 'mango', 'carrot', 'banana']
mylist = shoplist # mylist is just another name pointing to the same object!
del shoplist[0]
print 'shoplist is', shoplist
print 'mylist is', mylist
# notice that both shoplist and mylist both print the same list without
# the 'apple' confirming that they point to the same object
print 'Copy by making a full slice'
mylist = shoplist[:] # make a copy by doing a full slice
del mylist[0] # remove first item
print 'shoplist is', shoplist
print 'mylist is', mylist
# notice that now the two lists are different
輸出
$ python reference.py
Simple Assignment
shoplist is ['mango', 'carrot', 'banana']
mylist is ['mango', 'carrot', 'banana']
Copy by making a full slice
shoplist is ['mango', 'carrot', 'banana']
mylist is ['carrot', 'banana']
你需要記住的只是如果你想要復制一個列表或者類似的序
列或者其他復雜的對象(不是如整數那樣的簡單 對象 ),那么你必須使用切片操作符來取得
拷貝。如果你只是想要使用另一個變量名,兩個名稱都 引用 同一個對象,那么如果你不小心
的話,可能會引來各種麻煩。