簡體   English   中英

共享參考和平等

[英]Shared References and Equality

使用 Python 3.4 並通過 O'Reily 的書中的示例進行操作。 該示例顯示:

A = ['spam']
B = A
B[0] = 'shrubbery'

運行print A后的結果:

'shrubbery'

現在我的思考過程是A被定義但從未改變。

這個例子產生了不同的結果

A = 'string'
B = A
B = 'dog'

這是運行print A后的結果:

'string'

有人可以解釋嗎?

在第一個示例中,您正在修改B引用的列表。

正在做:

B[0] = 'shrubbery'

告訴 Python 將B引用的列表中的第一項設置為'shrubbery'的值。 此外,此列表恰好與A引用的列表相同。 這是因為這樣做:

B = A

導致BA各自引用同一個列表:

>>> A = ['spam']
>>> B = A
>>> A is B
True
>>>

因此,對B引用的列表的任何更改也會影響A引用的列表(反之亦然),因為它們是相同的 object。


然而,第二個示例沒有修改任何內容。 相反,它只是將名稱B重新分配給一個新值。

執行此行后:

B = 'dog'

B不再引用字符串'string'而是引用新字符串'dog' 同時A的值保持不變。

在此處輸入圖像描述

我希望你能用這種方式理解它:-)

正如您在第一種方法中看到的那樣,它們都引用同一個list ,第二個不同。所以在第二種方法中更改不會影響另一個。

與大多數現代動態語言一樣,python 中的變量實際上是類似於 C 指針的引用。 這意味着當您執行A = B之類的操作(其中 A 和 B 都是變量)時,您只需讓 A 指向 memory 中與 B 相同的位置。

在第一個示例中,您正在改變(修改)現有的 object ——這就是variable_name[index/key] = value語法的作用。 A 和 B 都繼續指向同一個東西,但這個東西的第一個條目現在是“灌木”,而不是“垃圾郵件”。

在第二個示例中,當您說B = 'dog'時,您將 B 指向不同的(此時是新的)object。

可變對象是列表,而字符串是不可變的,這就是為什么您可以更改 memory 地址和列表本身而不是字符串的原因。

我們在這里談論共享引用和可變/不可變對象。 當您執行 B = A 時,兩個變量都指向相同的 memory 地址(共享引用)。 第一種情況,列表是可變的 object (它的 state 可以更改)但 object ZCD69B4956F06CD8191ZBF3 地址保持不變 So if you change it's state, then the other variable will see those changes as it points to same memory address.( A and B have same value as they point to same object in memory ) Second case, string is immutable ( you cannot change it ). 通過執行 B = 'dog',基本上你創建了另一個 object,現在 B 指向另一個 object(另一個 memory 地址)。 在這種情況下,A 仍然指向相同的舊 memory 參考(A 和 B 具有不同的值)

以下是兩者之間的區別:

在此處輸入圖像描述

在此處輸入圖像描述

下面是一步一步的分析:

A = ['spam']
"A points to a list whose first element, or A[0], is 'spam'."
B = A
"B points to what A points to, which is the same list."
B[0] = 'shrubbery'
"When we set B[0] to 'shrubbery', the result can be observed in the diagram.
A[0] is set to 'shrubbery' as well."
print (A):



A = 'string'
"A points to 'string'."
B = A
"B points to what A points to, which is 'string'."
B = 'dog'
"Oh look! B points to another string, 'dog', now.
So does what A points to change? No."
The result can be observed in the diagram.
print (A):

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM