當(dāng)你創(chuàng)建一個(gè)對(duì)象并給它賦一個(gè)變量的時(shí)候,這個(gè)變量?jī)H僅 引用 那個(gè)對(duì)象,而不是表示這個(gè)
對(duì)象本身!也就是說(shuō),變量名指向你計(jì)算機(jī)中存儲(chǔ)那個(gè)對(duì)象的內(nèi)存。這被稱作名稱到對(duì)象的綁
定。
#!/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']
你需要記住的只是如果你想要復(fù)制一個(gè)列表或者類(lèi)似的序
列或者其他復(fù)雜的對(duì)象(不是如整數(shù)那樣的簡(jiǎn)單 對(duì)象 ),那么你必須使用切片操作符來(lái)取得
拷貝。如果你只是想要使用另一個(gè)變量名,兩個(gè)名稱都 引用 同一個(gè)對(duì)象,那么如果你不小心
的話,可能會(huì)引來(lái)各種麻煩。