Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

hash - Python: why can I put mutable object in a dict or set?

Given the following example,

class A(object):
    pass
a = A()
a.x = 1

Obviously a is mutable, and then I put a in a set,

set([a])

It succeeded. Why I can put mutable object like "a" into a set/dict? Shouldn't set/dict only allow immutable objects so they can identify the object and avoid duplication?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Python doesn't test for mutable objects, it tests for hashable objects.

Custom class instances are by default hashable. That's fine because the default __eq__ implementation for such classes only tests for instance identity and the hash is based of the same information.

In other words, it doesn't matter that you alter the state of your instance attributes, because the identity of an instance is immutable anyway.

As soon as you implement a __hash__ and __eq__ method that take instance state into account you might be in trouble and should stop mutating that state. Only then would a custom class instance no longer be suitable for storing in a dictionary or set.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...