3

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?

1

2 Answers 2

5

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)
Sign up to request clarification or add additional context in comments.

Comments

2

The current answer let's it appear as if there was a need to define __hash__. As a partly answer, I hence clarify that this is logically false.

One should be able to implement sha256 or the python interpreter such that of a given class object the full hash is taken.

Reason: With pickle dumps it is possible to save an object uniquely to file. The data footprint of that file is digestable; thus it is a mere insufficiency of the language and should be fixable through some boilerplate code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.