很多人分不清什么是可变类型什么是不可变类型。
在此之前,首先需要了解python的基本数据类型有哪些:
- Number(数字)
- String(字符串)
- List(列表)
- Tuple(元组)
- Set(集合)
- Dictionary(字典)
以上是python的6中基本数据类型。那么什么是可变类型和不可变类型呢?当修改变量的值,被引用对象发生了变化,这种数据类型称之为不可变类型。反之,当修改变量的值,被引用对象没有发生变化,这种数据类型称之为可变类型。简单来将,对于同一个变量:值变地址变,为不可变类型;值变地址不变,则为可变类型。(或者说,对于同一引用对象,值能变则为可变,值不能变则为不可变)
python中不可变数据类型有以下三种:
- Number(数字)
- String(字符串)
- Tuple(元组)
示例为变更以上三种数据类型的值时,变量对应内存地址的变化情况
>>> a = 10
>>> id(a)
1623549168
>>> a = 5
>>> id(a)
1623549088
>>>
>>> str1 = "hello"
>>> id(str1)
53409824
>>> str1 = "hello world"
>>> id(str1)
53427720
>>>
>>> tupleStr = (1, 12, 123)
>>> type(tupleStr)
<class 'tuple'>
>>> id(tupleStr)
53287232
>>> tupleStr = (1, 22, 123)
>>> id(tupleStr)
53287472
可变类型:
- List(列表)
- Set(集合)
- Dictionary(字典)
对于可变类型,我们可以看到当变量对应的值有变化时,变量指向的内存地址不随之变化:
>>> testList = [1, 2, 4, 5]
>>> id(testList)
53427856
>>> testList.append(8)
>>> id(testList)
53427856
>>> type(testList)
<class 'list'>>>> tset = set()
>>> id(tset)
53527536
>>> tset.add("tom")
>>> tset.add("test")
>>> tset
{'tom', 'test'}
>>> id(tset)
53527536
>>> tjson = {"a":1}
>>> id(tjson)
52909520
>>> tjson.update({"b":"haha"})
>>> tjson
{'a': 1, 'b': 'haha'}
>>> id(tjson)
52909520
当然,有人会说,我把值直接赋给list或者其他可变类型时,内存地址明明是变化的,如下图:
>>> tlist = [1, 2, 3]
>>> id(tlist)
53356824
>>> tlist = [1, 2, 3, 4]
>>> id(tlist)
53439152
在这里需要注意的是,用“=”进行赋值时,是对变量进行了初始化,python会根据对变量赋予的值的类型来决定变量的类型,并且重新分配内存地址
>>> tlist = [1, 2, 3]
>>> type(tlist)
<class 'list'>
>>> tlist = 1
>>> type(tlist)
<class 'int'>
以上为本人对于python可变和不可变类型的理解,如有不对,欢迎留言指正。