[英]What happens to a list reference when item is set
def foo():
testdict = {'A': '1235', 'B': '6458', 'C': 54156}
dofoo(testdict)
def dofoo(testdict):
testdict['A'] = testdict['A'].replace('2', '')
設置了testdict['A']
,引用testdict
變量的值會發生什么? 僅該項目丟失了對原始值的參考嗎?
編輯:
因為如果我願意:
def foo():
testdict = {'A': '1235', 'B': '6458', 'C': 54156}
dofoo(testdict)
def dofoo(testdict)
testdict = {'F' : '156', 'G' : '6875'}
然后,引用將丟失。 那為什么不設置這樣的收藏品呢?
testdict = {'A': '1235', 'B': '6458', 'C': 54156}
def foo(x):
x['A'] = 0;
foo(testdict)
print testdict['A']
testdict ['A']的輸出為0。
這是因為dict是作為引用傳遞給foo函數的。
因此,當您將testdict傳遞給foo時,x並不是一個新的dict,它是testdict的副本-實際上是指向同一testdict的指針。 當x ['A']改變時,這意味着testdict ['A']也改變了。
在任何給定時間了解給定名稱所指的值很重要。 這就是我的意思:
def doFoo1(testdict):
testdict["A"] = "test1" # this changes a value contained in testdict
print(id(testdict)) # the id
def doFoo2(testdict):
testdict = {some:"new dict"} # this creates a new dict object
print(id(testdict)) # prints a different id, since testdict is a new object
def foo():
mydict = {'A': '1235', 'B': '6458', 'C': 54156}
print(id(mydict))
doFoo1(mydict)
print(id(mydict))
doFoo2(mydict)
print(id(mydict))
這是我系統上的輸出(Windows 7上為64位Python 3.3):
>>> foo()
59383560
59383560
59383560
59413832
59383560
打印出五個id
值,從foo
打印三個(第一個,第三個和第五個),每個doFoo
函數一個(第二個和第四個)一個。 doFoo2中的一個是唯一與其他不同的一個,因為語句testdict = {some:"new dict"}
創建了一個新對象,該對象綁定到該函數名稱空間中的testdict
名稱。 該更改不會反映在foo
函數中,因為它的mydict
名稱仍綁定到原始對象。
這是Python的一部分,與大多數其他編程語言不同。 與C中變量名對應於內存中的特定位置不同,在Python中,名稱指的是特定對象。 如果再次分配該名稱,則只需將名稱重新綁定到其他對象(根本不影響原始對象,盡管如果沒有其他引用,則可能會被垃圾回收)。
該代碼的一部分(例如Pythonista演示文稿)對於理解這種區別非常有幫助。 我認為它的“名稱標簽”隱喻非常適合理解Python中名稱綁定的工作原理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.