Python:为什么我可以将可变对象放在 dict 或 set 中? [英] Python: why can I put mutable object in a dict or set?

查看:19
本文介绍了Python:为什么我可以将可变对象放在 dict 或 set 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出下面的例子,

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

显然 a 是可变的,然后我将 a 放入一个集合中,

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

set([a])

成功了.为什么我可以将像a"这样的可变对象放入 set/dict?set/dict 不应该只允许不可变对象,以便它们可以识别对象并避免重复吗?

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?

推荐答案

Python 不测试 mutable 对象,它测试 hashable 对象.

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

自定义类实例默认是可散列的.这很好,因为此类类的默认 __eq__ 实现仅测试实例 identity 并且哈希基于相同的信息.

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.

一旦您实现了一个将实例状态考虑在内的 __hash____eq__ 方法,您可能会遇到麻烦并且应该停止改变该状态.只有这样,自定义类实例才不再适合存储在字典或集合中.

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.

这篇关于Python:为什么我可以将可变对象放在 dict 或 set 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆