confusing doc: mutable and hashable

L

laymanzheng

I'm just learning Python. The python doc about mutable and hashable is confusing to me.

In my understanding, there is no directly relation between mutable and hashable in Python. Any class with __hash__ function is "hashable".

According the wiki: http://en.wikipedia.org/wiki/Immutable_object

In object-oriented and functional programming, an immutable object is an object whose state cannot be modified after it is created.[1] This is in contrast to a mutable object, which can be modified after it is created.

We surely can define __hash__ function in user-define class and the instance of that class can be changed thus mutable.

But following statement seems correct in practice but not technically. Any comments on this?

Thanks,
Andy
 
M

mwilson

I'm just learning Python. The python doc about mutable and hashable is
confusing to me.

In my understanding, there is no directly relation between mutable and
hashable in Python. Any class with __hash__ function is "hashable".

According the wiki: http://en.wikipedia.org/wiki/Immutable_object

In object-oriented and functional programming, an immutable object is an
object whose state cannot be modified after it is created.[1] This is in
contrast to a mutable object, which can be modified after it is created.

We surely can define __hash__ function in user-define class and the
instance of that class can be changed thus mutable.

But following statement seems correct in practice but not technically. Any
comments on this?

Wikipedia has it right. Mutable objects are objects where significant
attributes of the object can change value over the lifetime of the object.
This is useful for data sharing. If, for example, one part of your program
knows an object by the name `a`, and another part knows the same object as
`b` (or if they can access the object in any other distinct ways), they can
communicate by changing values of attributes of the shared object.

In practice, hashable means that the hashable object can be used as a key in
a dict. Looking up an item in a dict means that 1) the hash of the lookup
key has to match the hash of the stored key, and 2) the lookup key has to be
equal to the stored key according to the `==` operator. These requirements
are easy to meet if the keys are immutable. Otherwise for classes you
create, you can (if you're careful) create __hash__ and __eq__ methods to
meet the requirements, even if significant attributes of your instances can
change their values.

Mel.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top