Advertisement
NLinker

Don't use mutable keys

Jan 15th, 2019
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.64 KB | None | 0 0
  1. from https://gist.github.com/astynax/0f759f1527d6bdcf3d26c48837c59eb8
  2.  
  3. >>> class Point:
  4. ...     def __init__(self, x, y):
  5. ...         self.x, self.y = x, y
  6. ...     def __hash__(self):
  7. ...         return hash((self.x, self.y))
  8. ...     def __eq__(self, other):
  9. ...         return (self.x, self.y) == (other.x, other.y)
  10. ...     def __repr__(self):
  11. ...         return "Point({},{})".format(self.x, self.y)
  12. ...
  13. >>> p = Point(10, 20)
  14. >>> d = {p: 'a'}
  15. >>> d
  16. {Point(10,20): 'a'}
  17. >>> p.x += 1
  18. >>> d[p] = 'b'
  19. >>> d
  20. {Point(11,20): 'b', Point(11,20): 'a'}
  21. >>> ks = list(d.keys())
  22. >>> ks[0] == ks[1]
  23. True
  24. >>> hash(ks[0]) == hash(ks[1])
  25. True
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement