【发布时间】:2015-03-02 00:12:52
【问题描述】:
使用 Python 3.4 并研究 O'Reily 所著书籍中的示例。 示例显示:
A = ['spam']
B = A
B[0] = 'shrubbery'
运行print A后的结果:
'shrubbery'
现在我的想法是A 已定义但从未改变。
这个例子产生了不同的结果
A = 'string'
B = A
B = 'dog'
这是运行print A后的结果:
'string'
谁能解释一下?
【问题讨论】:
-
要详细了解构成这一切的 Python 内部内存模型的详细信息,我推荐 Wesley Chun 在 Understanding Python’s Memory Model & Mutability 上的演讲,他在 answer to a classic SO question 中引用了该演讲。尤其是第 9 页之后的内容正是关于这个问题的。
-
链接到video of the same presentation以获得更多的视听倾向。