Difference between hash() and id()

后端 未结 3 1830
情深已故
情深已故 2021-01-31 09:49

I have two user-defined objects, say a and b.
Both these objects have the same hash values.
However, the id(a) and

3条回答
  •  天涯浪人
    2021-01-31 10:19

    Unequal objects may have the same hash values.

    Yes this is true. A simple example is hash(-1) == hash(-2) in CPython.

    Equal objects need to have the same id values.

    No this is false in general. A simple counterexample noted by @chepner is that 5 == 5.0 but id(5) != id(5.0).

    Whenever, obj1 is obj2 is called, the id values of both the objects is compared, not their hash values.

    Yes this is true. is compares the id of the objects for equality (in CPython it is the memory address of the object). Generally, this has nothing to do with the object's hash value (the object need not even be hashable).

提交回复
热议问题