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

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

问题描述

给出以下示例,

Given the following example,

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

显然a是可变的,然后我把一个集合,

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

set([a])

成功了。为什么我可以把像a这样的可变对象放入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 对象,它会测试哈希对象。

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:为什么我可以在字典或集合中放置可变对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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