python 如何在幕后知道某物等于某物,它是否查看它们的内存位置

How does python know under the hood that something is equal to something, does it look at their memory location

我刚开始 python 并且我知道当你将一个变量设置为等于对象类型(如字符串)时,它们会使它们等价,但我想知道为什么 'abc' == 'abc' 是的,它是否检查了两个字符串的内存位置并发现它们具有相同的位置?还是 python 检查字符串的实际内部以查看每个字符是否匹配?

我知道这是一个基本的 python 问题,我理解为什么代码会输出我们看到的结果,但我想知道 python 在处理数据类型时如何检查相等性具有相同的构造。

'abc' == 'abc' #Output is True
'ab' == 'abc' #Output is False

相等运算符 == 检查相等性。 ab 是同一个字符串吗?

a = [1,2,3]
b = [1,2,3]
a == b  # True
a is b  # False

有一个 is 关键字将检查内存位置。

a = [1,2,3]
b = [1,2,3]
a is b # False
c = a
a is c  # True

值得注意的是,当与 is 关键字一起使用时,字符串的工作方式略有不同。

a = '123'
b = '123'
a == b  # True
a is b  # True

编辑:来自@Barmar "The reason for the last result is that immutable objects are interned, so it doesn't make multiple copies of equivalent strings."