Ori*_*ber 3 python variables pointers
我知道这是一个非常基本的问题,但我需要帮助理解这个简短的概念.
我正在学习Python,书中说"Python中的每个变量都是一个指向对象的指针.所以当你写出像y=x你这样的东西时,它们都会指向同一个对象.如果你改变原始对象,你会更改指向它的每个其他指针"
然后他们举个例子:
x=[1,2,3]
y=x
x[1]=3
print y
Run Code Online (Sandbox Code Playgroud)
它确实打印 [1,3,3]
但是,当我写下面的代码时:
x=5
y=x
x=7
print y
Run Code Online (Sandbox Code Playgroud)
它不打印7.它打印5.
为什么?
您的第一个示例可以解释如下:
x=[1,2,3] # The name x is assigned to the list object [1,2,3]
y=x # The name y is assigned to the same list object referenced by x
x[1]=3 # This *modifies* the list object referenced by both x and y
print y # The modified list object is printed
Run Code Online (Sandbox Code Playgroud)
但是,第二个示例仅将名称重新分配x给另一个整数对象:
x=5 # The name x is assigned to the integer object 5
y=x # The name y is assigned to the same integer object referenced by x
x=7 # The name x is *reassigned* to the new integer object 7
print y # This prints 5 because the value of y was never changed
Run Code Online (Sandbox Code Playgroud)
这是Python中赋值的参考.