开发者

Testing for reference equality in Python

Say I have a class in Python that has an eq method defined for comparing attributes for equality:

class Foo(object):
    # init code...

    def __eq__(self, other):
        # usual eq code here....

How can开发者_如何学Python I then compare two instances of Foo for reference equality (that is test if they are the same instance)? If I do:

f1 = Foo()
f2 = Foo()
print f1 == f2

I get True even though they are different objects.


Thats the is operator

print f1 is f2


f1 is f2 checks if two references are to the same object. Under the hood, this compares the results of id(f1) == id(f2) using the id builtin function, which returns a integer that's guaranteed unique to the object (but only within the object's lifetime).

Under CPython, this integer happens to be the address of the object in memory, though the docs mention you should pretend you don't know that (since other implementation may have other methods of generating the id).


Use the is keyword.

print f1 is f2

Some interesting things (that are implementation dependent I believe, but they are true in CPython) with the is keyword is that None, True, and False are all singleton instances. So True is True will return True.

Strings are also interned in CPython, so 'hello world' is 'hello world' will return True (you should not rely on this in normal code).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜