python - 如何检查不变性

标签 python python-2.7 python-3.x immutability mutable

<分区>

在 python 中,有什么方法可以检查对象是不可变的还是可变的?

isimmutable(a) 会返回 True,如果 a 是不可变的,否则返回 False

最佳答案

没有通用的不变性测试。仅当对象的任何方法都不能改变底层数据时,该对象才是不可变的。

看看这个question

答案是:

1) Keys must not be mutable, unless you have a user-defined class that is hashable but also mutable. That's all that's forced upon you. However, using a hashable, mutable object as a dict key might be a bad idea.

2) By not sharing values between the two dicts. It's OK to share the keys, because they must be immutable. Copying the dictionary, in the copy module sense, is definitely safe. Calling the dict constructor here works, too: b = dict(a). You could also use immutable values.

3) All built-in immutable types are hashable. All built-in mutable types are not hashable. For an object to be hashable, it must have the same hash over its entire lifetime, even if it is mutated.

4) Not that I'm aware of; I'm describing 2.x.

A type is mutable if it is not immutable. A type is immutable if it is a built-in immutable type: str, int, long, bool, float, tuple, and probably a couple others I'm forgetting. User-defined types are always mutable.

An object is mutable if it is not immutable. An object is immutable if it consists, recursively, of only immutable-typed sub-objects. Thus, a tuple of lists is mutable; you cannot replace the elements of the tuple, but you can modify them through the list interface, changing the overall data

这应该回答你的问题

关于python - 如何检查不变性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17875177/

相关文章:

python - 将列表与列表列表合并

python - 读取并检查文件中的连续单词

python-3.x - 慢序列化过程 Django rest 框架

python - 使用元图 tensorflow 运行模型失败

python - 使用 Jinja2 嵌套 For 循环迭代连接表中的数据

Python:为什么我的 Click CLI 没有执行所需的功能?

Python py2exe 窗口显示 (tkinter)

python - 在 python 上使用参数调用函数

python - 为什么 Python/Django 不会在 Mysql : ERROR 1205 (HY000): Lock wait timeout exceeded 上引发异常

python - `in` 运算符链接出现意外结果