python的值類型:int,str,tuple --- 元素不可變的,要改變只能重新聲明或者覆蓋
python的引用類型:set,list,dict --- 元素的值時可變的
值類型不可變
>>> a = 1
>>> b = a
>>> print(a)
1
>>> print(b)
1
>>> a = 3
>>> print(a)
3
>>> print(b)
1
引用類型可以變
>>> a = [1,2,3]
>>> b = a
>>> print(a)
[1, 2, 3]
>>> print(b)
[1, 2, 3]
>>> print(a[0])
1
>>> a[0] = "1"
>>> print(a)
['1', 2, 3]
>>> print(b)
['1', 2, 3]
>>> a = "hello"
>>> id(a)
2552494650512
>>> a = a + "python"
>>> print(a)
hellopython
>>> id(a)
2552494593072
id() --- 查看內存地址
str確實時不可改變的,但是這里a+"pytho"得到的是一個新的字符串,因為a的地址改變了,所有並沒有違背str的值的不可改變的性質
>>> "python"[0]
'p'
>>> "python"[0] = "a"
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
"python"[0] = "a"
TypeError: 'str' object does not support item assignment
上述的代碼體現了str的不可改變性,因為在取值時並不改變str,所以可以正常的取,但是試圖把python的第一個字母改為a的時候會報錯,因為str不可改變。
