我对什么是不可变类型感到困惑。我知道float对象被认为是不可变的,我的书中有这样的例子:

class RoundFloat(float):
    def __new__(cls, val):
        return float.__new__(cls, round(val, 2))

因为类结构/层次结构,这被认为是不可变的吗?,这意味着float位于类的顶部,是它自己的方法调用。类似于这种类型的例子(即使我的书说dict是可变的):

class SortedKeyDict(dict):
    def __new__(cls, val):
        return dict.__new__(cls, val.clear())

然而,可变的东西在类中有方法,例如:

class SortedKeyDict_a(dict):
    def example(self):
        return self.keys()

同样,对于最后一个类(SortedKeyDict_a),如果我将这种类型的set传递给它:

d = (('zheng-cai', 67), ('hui-jun', 68),('xin-yi', 2))

不调用示例方法,它将返回一个字典。带有__new__的SortedKeyDict将其标记为错误。我尝试用__new__将整数传递给RoundFloat类,它没有标记错误。


当前回答

看待差异的一种方式是:

在python中,对不可变对象的赋值可以被认为是深度拷贝, 而对可变对象的赋值是浅的

其他回答

我没有阅读所有的答案,但所选的答案是不正确的,我认为作者有一个想法,即能够重新分配变量意味着任何数据类型都是可变的。事实并非如此。可变性与通过引用传递而不是通过值传递有关。

假设您创建了一个List

a = [1,2]

如果你说:

b = a
b[1] = 3

即使你在B上重新分配了一个值,它也会重新分配a上的值。这是因为当你分配“B = a”时。您传递给对象的是“Reference”,而不是值的副本。而字符串、浮点数等则不是这样。这使得列表、字典和类似的东西是可变的,但是布尔值、浮点数等是不可变的。

如果你是从另一种语言(除了一种非常像Python的语言,比如Ruby)学习Python的,并且坚持用另一种语言来理解它,下面是人们通常会感到困惑的地方:

>>> a = 1
>>> a = 2 # I thought int was immutable, but I just changed it?!

在Python中,赋值不是突变。

在c++中,如果你写a = 2,你是在调用a.operator=(2),这将改变存储在a中的对象(如果a中没有存储对象,这是一个错误)。

在Python中,a = 2对存储在a;它只是意味着2现在存储在a中。(如果a中没有存储对象,也没关系。)


归根结底,这是更深层次区别的一部分。

在c++这样的语言中,变量是内存中的类型化位置。如果a是int型,这意味着它有4个字节,编译器知道它应该被解释为int型。当你令a = 2时,它改变了存储在这4个字节内存中的内容从0,0,0,1变成了0,0,0,2。如果在其他地方有另一个int变量,它有自己的4个字节。

A variable in a language like Python is a name for an object that has a life of its own. There's an object for the number 1, and another object for the number 2. And a isn't 4 bytes of memory that are represented as an int, it's just a name that points at the 1 object. It doesn't make sense for a = 2 to turn the number 1 into the number 2 (that would give any Python programmer way too much power to change the fundamental workings of the universe); what it does instead is just make a forget the 1 object and point at the 2 object instead.


如果赋值不是突变,那么什么是突变呢?

Calling a method that's documented to mutate, like a.append(b). (Note that these methods almost always return None). Immutable types do not have any such methods, mutable types usually do. Assigning to a part of the object, like a.spam = b or a[0] = b. Immutable types do not allow assignment to attributes or elements, mutable types usually allow one or the other. Sometimes using augmented assignment, like a += b, sometimes not. Mutable types usually mutate the value; immutable types never do, and give you a copy instead (they calculate a + b, then assign the result to a).

但如果赋值不是突变,那么对象的一部分赋值是如何突变的呢?这就是棘手的地方。a[0] = b不会改变[0](再次,不像c++),但它会改变a(不像c++,除非是间接的)。

这就是为什么最好不要尝试按照您习惯的语言来理解Python的语义,而是根据Python的语义来学习Python的语义。

这个答案的目标是创建一个单独的地方来找到所有关于如何判断您正在处理的是突变/非突变(不可变/可变)的好想法,以及在可能的情况下如何处理它?有些时候,突变是不受欢迎的,python在这方面的行为可能会让来自其他语言的编码人员感到违反直觉。

根据@mina-gabriel的一篇有用的文章:

可能会有帮助的书籍:《Python中的数据结构和算法》 摘自那本书,列出了可变/不可变类型: 可变/不可变类型图像

分析以上并结合@arrakëën的文章:

什么不会意外改变?

标量(存储单个值的变量类型)不会意外变化 数值示例:int(), float(), complex() 有一些“可变序列”: Str (), tuple(), frozenset(), bytes()

可以什么?

类似对象的列表(lists, dictionary, sets, bytearray()) 这里的一篇文章也提到了类和类实例,但这可能取决于类继承了什么和/或它是如何构建的。

我所说的“意外”是指来自其他语言的程序员可能没有预料到这种行为(除了Ruby和其他一些“类似Python”的语言)。

在这个讨论中补充:

这种行为是一种优势,因为它可以防止您意外地用多个占用内存的大型数据结构的副本填充代码。但当这种情况不受欢迎时,我们该如何解决呢?

对于列表,简单的解决方案是构建一个新的列表,如下所示:

列表 2 = 列表(列表 1)

对于其他结构……解决方案可能更加棘手。一种方法是遍历元素并将它们添加到新的空数据结构(相同类型)。

当传入可变结构时,函数可以改变原始值。如何分辨?

There are some tests given on other comments on this thread but then there are comments indicating these tests are not full proof object.function() is a method of the original object but only some of these mutate. If they return nothing, they probably do. One would expect .append() to mutate without testing it given its name. .union() returns the union of set1.union(set2) and does not mutate. When in doubt, the function can be checked for a return value. If return = None, it does not mutate. sorted() might be a workaround in some cases. Since it returns a sorted version of the original, it can allow you to store a non-mutated copy before you start working on the original in other ways. However, this option assumes you don't care about the order of the original elements (if you do, you need to find another way). In contrast .sort() mutates the original (as one might expect).

非标准方法(以防有用): 在github上发现了这个,在MIT许可下发布:

Github仓库下:tobgu命名为:pyrsistent 它是什么:Python持久化数据结构代码,用于在不希望发生变化时代替核心数据结构

对于自定义类,@分号建议检查是否有__hash__函数,因为可变对象通常不应该有__hash__()函数。

这就是我目前在这个话题上所收集到的全部信息。欢迎提出其他意见、纠正意见等。谢谢。

你必须理解Python将所有数据表示为对象。其中一些对象(如列表和字典)是可变的,这意味着您可以在不改变其标识的情况下更改其内容。其他对象,如整数、浮点数、字符串和元组是不能更改的对象。 一个简单的理解方法是看一下对象ID。

下面是一个不可变的字符串。你不能改变它的内容。如果您试图更改它,它将引发TypeError。同样,如果我们分配新内容,则创建一个新对象,而不是修改内容。

>>> s = "abc"
>>> id(s)
4702124
>>> s[0] 
'a'
>>> s[0] = "o"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> s = "xyz"
>>> id(s)
4800100
>>> s += "uvw"
>>> id(s)
4800500

你可以用一个列表这样做,它不会改变对象的身份

>>> i = [1,2,3]
>>> id(i)
2146718700
>>> i[0] 
1
>>> i[0] = 7
>>> id(i)
2146718700

要阅读更多关于Python的数据模型,你可以看看Python语言参考:

双重指控 斑马3套指控模型

看待差异的一种方式是:

在python中,对不可变对象的赋值可以被认为是深度拷贝, 而对可变对象的赋值是浅的