Python; name bindings are not object references?

大城市里の小女人 提交于 2019-12-24 00:47:22

问题


I am trying to understand what exactly a Python name binding is, and when this binding is interpreted.

In c,

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

prints 666. I was expecting the block of Python code:

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

to do the same, but it does not. What exactly happens between the lines labeled 3 and 5? Does #3 make another reference to the object known as "42", like X, lets call it X', and store X' in the object pointed to by L, which is []?


回答1:


What you state is almost what happens:

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.

The append is not binding the array element to the X, it's binding it to the object behind X, which is the 42.

When I first realised this is the way Python worked, things (specifically, things like this which had previously confused me and caused much angst and gnashing of teeth) became so much clearer.



来源:https://stackoverflow.com/questions/33115204/python-name-bindings-are-not-object-references

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!