简体   繁体   中英

When you override __eq__ in a class, do you also need to override __hash__?

I'm making a node class in Python 3 which I will be storing in a min-ordered multi-tree structure. I overrode the __eq__ method which tests for equality by comparing two unique integer instance variables.

  1. Will this approach work for finding nodes in the structure by comparing equality?
  2. Do I also need to override __hash__ ?

Yes, you have to override __hash__ .

The general rule is: if two instances are equal (wrt to __eq__ , ie a==b is True), then they must have the same hash. Otherwise, all sorts of things can misbehave.

Also, it sounds to me __eq__ is not enough for minimum. At the very least, you'd need to define __lt__ .

I'm making a node class in Python 3 which I will be storing in a min-ordered multi-tree structure

If it's the only use, and they are only used internally so user code isn't ever supposed to see a Node , and your code doesn't store them in dicts or sets, or call any functions which do, maybe you can get away without overriding __hash__ .

But those are very strong restrictions, which can't really be enforced. And there's no benefit to not overriding __hash__ to be consistent with __eq__ . So you still should do it.

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