关于immutability:为什么Python中存在不可变对象?

Why are there immutable objects in Python?

本问题已经有最佳答案,请猛点这里访问。

所以python是通过引用传递的。总是。但是像整数、字符串和元组这样的对象,即使传递到函数中,也不能更改(因此它们被称为不可变的)。下面是一个例子。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def foo(i, l):
  i = 5 # this creates a new variable which is also called i
  l = [1, 2] # this changes the existing variable called l

i = 10
l = [1, 2, 3]
print(i)
# i = 10
print(l)
# l = [1, 2, 3]
foo(i, l)
print(i)
# i = 10 # variable i defined outside of function foo didn't change
print(l)
# l = [1, 2] # l is defined outside of function foo did change

所以可以看到整型对象是不可变的,而列表对象是可变的。

在python中使用不可变对象的原因是什么?如果所有的对象都是可变的,那么对于像Python这样的语言有什么好处和缺点呢?


您的示例不正确。lfoo()范围外没有变化。ilfoo()内部是指向新物体的新名称。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Python 2.7.10 (default, Aug 22 2015, 20:33:39)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.1)] on darwin
Type"help","copyright","credits" or"license" for more information.
>>> def foo(i, l):
...   i = 5 # this creates a local name i that points to 5
...   l = [1, 2] # this creates a local name l that points to [1, 2]
...
>>> i = 10
>>> l = [1, 2, 3]
>>> print(i)
10
>>> print(l)
[1, 2, 3]
>>> foo(i, l)
>>> print(i)
10
>>> print(l)
[1, 2, 3]

现在,如果你把foo()改为突变l,情况就不同了。

1
2
3
4
5
6
>>> def foo(i, l):
...     l.append(10)
...
>>> foo(i, l)
>>> print(l)
[1, 2, 3, 10]

python 3示例相同

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type"help","copyright","credits" or"license" for more information.
>>> def foo(i, l):
...   i = 5 # this creates a new variable which is also called i
...   l = [1, 2] # this changes the existing variable called l
...
>>> i = 10
>>> l = [1, 2, 3]
>>> print(i)
10
>>> print(l)
[1, 2, 3]
>>> foo(i, l)
>>> print(i)
10
>>> print(l)
[1, 2, 3]