Ada*_*kin 26 python equality reference
假设我在Python中有一个类,它有一个eq方法,用于比较属性是否相等:
class Foo(object):
# init code...
def __eq__(self, other):
# usual eq code here....
Run Code Online (Sandbox Code Playgroud)
然后我如何比较两个Foo实例的参考相等性(即如果它们是同一个实例则测试)?如果我做:
f1 = Foo()
f2 = Foo()
print f1 == f2
Run Code Online (Sandbox Code Playgroud)
即使它们是不同的对象,我也是真的.
使用is关键字。
print f1 is f2
Run Code Online (Sandbox Code Playgroud)
一些有趣的事情(我相信这些是依赖于实现的,但它们在 CPython 中是正确的),关键字is是 None、True 和 False 都是单例实例。所以True is True会返回True。
字符串也在 CPython 中驻留,因此'hello world' is 'hello world'将返回 True(您不应该在正常代码中依赖于此)。
f1 is f2检查两个引用是否指向同一个对象。在幕后,这比较了id(f1) == id(f2)使用id内置函数的结果,该函数返回一个整数,该整数保证对对象唯一(但仅限于对象的生命周期内)。
在 CPython 下,这个整数恰好是对象在内存中的地址,尽管文档提到你应该假装你不知道(因为其他实现可能有其他生成 id 的方法)。