为什么 Python 中有不可变对象?

Why are there immutable objects in Python?

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

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 这样的语言会有什么优点和缺点?

您的示例不正确。 l 没有foo() 的范围之外进行更改。 ifoo() 内的 l 是指向新对象的新名称。

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,那就是另外一回事了

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

Python3例同

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]