2 ms·
In order to use a standard hash function, you would first need to serialize the object. I am not aware of any programing language that does this. Instead, the
by gizmo686 9y ago
In order to use a standard hash function, you would first need to serialize the object. I am not aware of any programing language that does this.
Instead, the approach taken by (at least) Java and Python, is to define a "hash" function of objects, the classes can overwrite. The standard way of implementing such a function is to combine the hashes of the objects fields.
Python advises doing this by wrapping them in a tuple, and returning hash(self.a, self.b, ...). [1]
Java takes a simmilar approach, but does not make an explicit recomandation on how to implement hashCode(). In my experience, most programmers just XOR the hash of the fields, which (depending on the object) could be very sub-optimal, but is often good enough. Based on the doc, the typical implementation for Object.hashCode is to just take the memory address of the object.
[0] https://docs.python.org/3/reference/datamodel.html#object.__hash__ https://docs.python.org/3/reference/datamodel.html#object.__...
[1] Pythons tuple hash function may be found here: https://hg.python.org/cpython/file/dcced3bd22fe/Objects/tupleobject.c https://hg.python.org/cpython/file/dcced3bd22fe/Objects/tupl...
[2] https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode() https://docs.oracle.com/javase/7/docs/api/java/lang/Object.h...
- jwilk 9y agoPython has migrated from hg to git. The current version of tupleobject.c is here: https://github.com/python/cpython/blob/master/Objects/tupleobject.c https://github.com/python/cpython/blob/master/Objects/tupleo...