gpt4 book ai didi

python - 列表与 int 分配 - "Every variable is a pointer"

转载 作者:太空宇宙 更新时间:2023-11-03 13:43:54 24 4
gpt4 key购买 nike

我知道这是一个非常基本的问题,但我需要帮助来理解这个简短的概念。

我正在学习 Python,书上说“Python 中的每个变量都是指向对象的指针。所以当你写类似 y=x 的东西时,你实际上是在让它们都指向同一个对象。如果你改变原始对象,你将改变指向它的所有其他指针“

然后他们举了一个例子:

x=[1,2,3]
y=x
x[1]=3
print y

它确实打印了[1,3,3]

但是,当我写下下面的代码时:

x=5
y=x
x=7
print y

它不打印 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

但是,第二个示例仅将名称 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

这里是关于 assignment in Python 的引用.

关于python - 列表与 int 分配 - "Every variable is a pointer",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24478144/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com