Shared References and Equality
使用python 3.4并通过O'reily的书中的示例进行工作。示例显示:
1 2 3 | A = ['spam'] B = A B[0] = 'shrubbery' |
运行
1 | 'shrubbery' |
现在我的思维过程是,
这个例子产生了不同的结果
1 2 3 | A = 'string' B = A B = 'dog' |
这是运行
1 | 'string' |
有人能解释吗?
在第一个示例中,您正在修改
做:
1 | B[0] = 'shrubbery' |
告诉python将
1 | B = A |
使
1 2 3 4 5 | >>> A = ['spam'] >>> B = A >>> A is B True >>> |
因此,对
但是,第二个示例不修改任何内容。相反,它只是将名称
执行此行后:
1 | B = 'dog' |
与大多数现代动态语言一样,Python中的变量实际上是引用,类似于C指针。这意味着,当您执行类似于
在第一个示例中,您正在改变(修改)现有的对象——这就是
在第二个例子中,当你说
我希望你能这样理解它:—)
正如您在第一种方法中看到的,它们都引用相同的
以下是两者的区别:
下面是一个逐步分析:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | A = ['spam'] "A points to a list whose first element, or A[0], is 'spam'." B = A "B points to what A points to, which is the same list." B[0] = 'shrubbery' "When we set B[0] to 'shrubbery', the result can be observed in the diagram. A[0] is set to 'shrubbery' as well." print (A): A = 'string' "A points to 'string'." B = A "B points to what A points to, which is 'string'." B = 'dog' "Oh look! B points to another string, 'dog', now. So does what A points to change? No." The result can be observed in the diagram. print (A): |