我想澄清一下 Python 中的简单指针机制。考虑以下因素:
u = [1,2]
v = [u,3]
print(v)
u[0] = 100
print(v)
那么结果就是
[[1,2],3]
[[100,2],3]
同时如果我们执行
u = [1,2]
v = [u,3]
print(v)
u = [100,2]
print(v)
那么结果就是
[[1,2],3]
[[1,2],3]
我认为发生这种情况是因为在第一个代码中, u
的指针在第二个代码中,存储 u
的指针始终没有改变。店铺变更声明u=[100,2]
但声明v=[u,3]
存储了初始指针本身而不是变量 u
.
对于发生这种情况的原因,这是正确的解释吗?
最佳答案
Python 没有指针的概念,用指针来思考 Python 结构可能会产生误导。 Python 有名称和对对象的引用,而不是指针(Python 中一切都是对象)。
赋值运算符 (=
) 用于通过引用将名称绑定(bind)到对象。当您使用名称访问对象时,您将获得对象而不是引用。您无法访问引用的值,也无法像 C 中的指针运算那样操作引用。考虑到这一点,让我用 Python 术语分解您的代码:
# A new list object is created and bound to the name `u`.
# It only has `int` elements which are immutable
u = [1,2]
# A different list object is created and bound to the name `v`.
# Its first element is an other list object which is bound to the name `u` at this point.
v = [u,3]
print(v)
# __setitem__(0, 100) is called on the list object under the name `u`
# The first element of `v` remains this altered object.
u[0] = 100
print(v)
# Same as before
u = [1,2]
v = [u,3]
print(v)
# A new list object is created and bound to the name `u`.
# The previous list object bound to `u` remains the first element of `v` which is unchanged.
u = [100,2]
print(v)
希望这有帮助
关于python - Python 中的列表指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59513657/