我对什么是不可变类型感到困惑。我知道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类,它没有标记错误。


当前回答

例如,对于不可变对象,赋值会创建一个新的值副本。

x=7
y=x
print(x,y)
x=10 # so for immutable objects this creates a new copy so that it doesnot 
#effect the value of y
print(x,y)

对于可变对象,赋值操作不会创建值的另一个副本。例如,

x=[1,2,3,4]
print(x)
y=x #for immutable objects assignment doesn't create new copy 
x[2]=5
print(x,y) # both x&y holds the same list

其他回答

每次我们改变一个不可变变量的值时,它基本上会破坏之前的实例并创建一个变量类的新实例

var = 2 #Immutable data
print(id(var))
var += 4
print(id(var))

list_a = [1,2,3] #Mutable data
print(id(list_a))
list_a[0]= 4
print(id(list_a))

输出:

9789024
9789088
140010877705856
140010877705856

注意:可变变量memory_location在改变值时为change

什么?浮点数是不可变的?但我做不到

x = 5.0
x += 7.0
print x # 12.0

那不是"mut" x吗?

你同意字符串是不可变的,对吧?但你可以做同样的事情。

s = 'foo'
s += 'bar'
print s # foobar

变量的值会改变,但改变的方式是改变变量所指向的对象。可变类型可以这样改变,也可以“就地”改变。

区别就在这里。

x = something # immutable type
print x
func(x)
print x # prints the same thing

x = something # mutable type
print x
func(x)
print x # might print something different

x = something # immutable type
y = x
print x
# some statement that operates on y
print x # prints the same thing

x = something # mutable type
y = x
print x
# some statement that operates on y
print x # might print something different

具体的例子

x = 'foo'
y = x
print x # foo
y += 'bar'
print x # foo

x = [1, 2, 3]
y = x
print x # [1, 2, 3]
y += [3, 2, 1]
print x # [1, 2, 3, 3, 2, 1]

def func(val):
    val += 'bar'

x = 'foo'
print x # foo
func(x)
print x # foo

def func(val):
    val += [3, 2, 1]

x = [1, 2, 3]
print x # [1, 2, 3]
func(x)
print x # [1, 2, 3, 3, 2, 1]

可变和不可变对象之间的区别

定义

可变对象:创建后可以更改的对象。 不可变对象:创建后不能更改的对象。

在Python中,如果你改变了不可变对象的值,它会创建一个新对象。

可变的对象

下面是Python中可变类型的对象:

列表 字典 集 中bytearray 用户定义的类

不可变对象

以下是Python中不可变类型的对象:

int 浮动 小数 复杂的 保龄球 字符串 元组 范围 frozenset 字节

一些悬而未决的问题

问:字符串是不可变类型吗? 回答:是的,但你能解释一下吗? 证据1:

a = "Hello"
a +=" World"
print a

输出

"Hello World"

在上面的例子中,字符串被创建为“Hello”,然后更改为“Hello World”。这意味着字符串是可变类型的。但当我们检查它的标识,看它是否为可变类型时,就不是这样了。

a = "Hello"
identity_a = id(a)
a += " World"
new_identity_a = id(a)
if identity_a != new_identity_a:
    print "String is Immutable"

输出

String is Immutable

证据2:

a = "Hello World"
a[0] = "M"

输出

TypeError 'str' object does not support item assignment

问:元组是不可变类型吗? 答案:是的。 证据1:

tuple_a = (1,)
tuple_a[0] = (2,)
print a

输出

'tuple' object does not support item assignment

最简单的答案:

可变变量的值可能会在某个位置发生变化,而不可变变量的值不会在某个位置发生变化。修改不可变变量将重新构建相同的变量。

例子:

>>>x = 5

是否会创建一个由x引用的值5

X ->

>>>y = x

这个表述使y = 5 (x

X -------------> 5 <-----------y

>>>x = x + y

由于x是一个整数(不可变类型)已重新构建。

在语句中,RHS上的表达式将得到值10,当它被赋值给LHS (x)时,x将重新构造为10。所以现在

x ---------> 10

y ---------> 5

这个答案的目标是创建一个单独的地方来找到所有关于如何判断您正在处理的是突变/非突变(不可变/可变)的好想法,以及在可能的情况下如何处理它?有些时候,突变是不受欢迎的,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__()函数。

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