2015-10-14 18 views
2

我想了解Python名稱綁定是什麼,以及何時解釋此綁定。Python;名稱綁定不是對象引用?

在C,

include <stdio.h> 
int main() 
{ 
int X = 42; 
int* Y[1]; 
Y[0] = &X; 
X = 666; 
printf("%d", *Y[0]); 
return 0; 
} 

打印666我期待的Python代碼塊:

X = 42 
L = [] 
L.append(X) #3 
X = 666 
print(L) #5 

做同樣的,但事實並非如此。標記爲3和5的行之間究竟發生了什麼? #3是否使對另一個引用稱爲「42」的對象,如X,讓它稱爲X',並將X'存儲在由L指向的對象中,該對象是[]?

回答

5

什麼,你狀態幾乎會發生什麼:

X = 42    # Create new object 42, bind name X to it. 
L = [] 
L.append(X)   # Bind L[0] to the 42 object. 
X = 666    # Create new object 666, bind name X to it. 
print(L)    # Will not see the 666. 

append數組元素結合到X,它是將它綁定到後面X的對象,這是42

當我第一次意識到這是Python的工作方式時,事情(特別是之前讓我困惑並引起很多焦慮和咬牙切齒的事情)變得更加清晰。

相關問題