2015-10-14 45 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

答案是對的。這個問題和例子是錯誤的。 –

相關問題