Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate hash of object , python

I have a class with string data, and I'm supposed to calculate hash of the whole object using hashlib.sha256() . I was not directly able to get hash with block c for example

Hash = hashlib.sha256(c.encode()).digest()

I want to calculate hash of the whole object,I was suggested to have a function in the class such that it returns hash of data inside it . Is it same as has of whole block ? What is better implementation?

like image 984
Mark-III Avatar asked Jul 27 '26 14:07

Mark-III


1 Answers

You need to implement the magic method __hash__ for your class. You may then use an instance of your class, for example, as a key of a dictionary. Also, if you just need to get a hash, you can simply use the built-in function hash():

   c = MyClass()
   c_hash = hash(c)
like image 52
JOHN_16 Avatar answered Jul 30 '26 04:07

JOHN_16



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!