Note that there are some explanatory texts on larger screens.

plurals
  1. POExplanation needed regarding explanation of hashable objects
    primarykey
    data
    text
    <p><a href="https://stackoverflow.com/users/5987/mark-ransom">Mark Ransom</a> answered on a <a href="https://stackoverflow.com/questions/2671376/hashable-immutable/2671476#2671476">SO question about hashes</a> here in SO:</p> <blockquote> <p>[...] An object is hashable if it has a hash value <strong>which never changes during its lifetime</strong>. So by the official definition, anything mutable can't be hashable, even if it has a <code>__hash__()</code> function. My statement about both requirements being necessary is untrue, because being hashable already implies the requirement to be immutable.</p> </blockquote> <p>I want to make sure, that I got that right - even as a non native speaker - so I hope someone corrects me if I got it wrong.</p> <p>Assuming this class</p> <pre><code>class Author(object): def __init__(self, id, name, age): self.id = id self.name = name self.age = age def __eq__(self, other): return self.id==other.id\ and self.name==other.name def __hash__(self): return hash(('id', self.id, 'name', self.name)) </code></pre> <p>I understand, that <code>__eq__</code> allows me to compare objects of this class with the <code>==</code> operator. From Marks answer I understand, that even if my object <code>peter = Author(1, "Peter", 33)</code> has a <code>__hash__</code> it is not hashable because I potentially could do something like <code>peter.age = 43</code> which means it is not immutable. So my objects of the class <code>Author</code> are not hashable and therefore not usable as keys in dictionarys for example? Did I get right or does it seem, that I need more explanation? :-)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload