Is there a way to generate a hash-like ID in for objects in python that is solely based on the objects' attribute values? For example,
class test:
def __init__(self, name):
self.name = name
obj1 = test('a')
obj2 = test('a')
hash1 = magicHash(obj1)
hash2 = magicHash(obj2)
What I'm looking for is something where hash1 == hash2. Does something like this exist in python? I know I can test if obj1.name == obj2.name, but I'm looking for something general I can use on any object.
creating a unique random id To create a random id, you call the uuid4 () method and it will automatically generate a unique id for you just as shown in the example below; Example of usage.
The id is unique only as long as an object is alive. Objects that have no references left to them are removed from memory, allowing the id() value to be re-used for another object, hence the non-overlapping lifetimes wording. Note that this applies to CPython only, the standard implementation provided by python.org.
Python id() FunctionThe id() function returns a unique id for the specified object. All objects in Python has its own unique id. The id is assigned to the object when it is created.
You mean something like this?
Using the special method __hash__
class test:
def __init__(self, name):
self.name = name
def __hash__(self):
return hash(self.name)
>>> hash(test(10)) == hash(test(20))
False
>>> hash(test(10)) == hash(test(10))
True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With