2015-10-14 77 views
-2

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

+0

不可变对象更快。 – TigerhawkT3

+3

关于数字'1',你可能会改变什么? –

+0

@ TigerhawkT3我可以看到这是怎么回事,但是即使一些常用的对象速度很慢,语言也可能具有范式优势。 – bourbaki4481472

回答

0

你的例子不正确。 l没有更改foo()的范围以外。 il里面的foo()是指向新对象的新名称。现在

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] 

Python 3的实例相同

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] 
+0

哦,这实际上是我想说的更清晰的例子! – bourbaki4481472

+0

我认为这可能是错误的。新的变量没有被创建,相同的参数变量只是被重新分配。这里有一个演示:http://ideone.com/LJt4AY。也就是说,我不明白这是如何回答这个问题的(即为什么Python中有不可变对象)。 –

+0

答案是对的。这个问题和例子是错误的。 –

相关问题