简体   繁体   中英

user-defined class: hash() and id() and doc

According to the doc:

Objects which are instances of user-defined classes are hashable by default; they all compare unequal (except with themselves), and their hash value is their id().

Now from console:

class ABC:
  def __init__(self):
    pass

a = ABC()
id(a)
140102888165648
hash(a)
8756430510353

Shoudln't a have the same hash and id value?

According to the documentation for __hash__()

User-defined classes have __cmp__() and __hash__() methods by default; with them, all objects compare unequal (except with themselves) and x.__hash__() returns a result derived from id(x) .

It seems like the glossary is either outdated or inaccurate.


The documentation for python3's __hash__ is slightly different:

User-defined classes have __eq__() and __hash__() methods by default; with them, all objects compare unequal (except with themselves) and x.__hash__() returns an appropriate value such that x == y implies both that x is y and hash(x) == hash(y) .

So they even removed the fact that such value should depend on id .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM