python的值类型和引用类型

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不可改变。

 

posted on 2019-07-25 15:17  递弱代偿  阅读(2374)  评论(1编辑  收藏  举报

导航