设为首页 加入收藏

TOP

python 可变对象和不可变对象
2017-12-18 12:37:23 】 浏览:83
Tags:python 可变 对象

不可变对象,该对象所指向的内存中的值不能被改变。当改变某个变量时候,由于其所指的值不能被改变,相当于把原来的值复制一份后再改变,这会开辟一个新的地址,变量再指向这个新的地址。

可变对象,该对象所指向的内存中的值可以被改变。变量(准确的说是引用)改变后,实际上是其所指的值直接发生改变,并没有发生复制行为,也没有开辟新的地址,通俗点说就是原地改变

python中,int,float,string,tuple,bytes为不可变对象,set,list,dict为可变对象。

int:

1 >>> a = 10
2 >>> id(a)
3 140289936218048
4 >>> a = a + 1
5 >>> id(a)
6 140289936218024
View Code

float:

1 >>> a = 10.55
2 >>> id(a)
3 140289936226024
4 >>> a = a + 1.5
5 >>> id(a)
6 140289936226000
View Code

string:

1 >>> a = 'abc'
2 >>> id(a)
3 4356135112
4 >>> a = a + 'd'
5 >>> id(a)
6 4357016240
View Code

tuple:

1 >>> a = (1, 2, 3)
2 >>> id(a)
3 4356913584
4 >>> a = (4, 5, 6)
5 >>> id(a)
6 4356799536
View Code

bytes:

1 >>> a = b'abc'
2 >>> id(a)
3 4356135112
4 >>> a = a + 'def'
5 >>> id(a)
6 4357016288
View Code

set:

1 >>> a = set([1, 2, 3])
2 >>> id(a)
3 4356754224
4 >>> a.add(4)
5 >>> id(a)
6 4356754224
View Code

list:

1 >>> a = [1, 2, 3]
2 >>> id(a)
3 4356905656
4 >>> a.append(4)
5 >>> id(a)
6 4356905656
View Code

dict:

1 >>> a = {'one': 1, 'two': 2}
2 >>> id(a)
3 4357024576
4 >>> a['three'] = 3
5 >>> id(a)
6 4357024576
View Code

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇python string类型 bytes类型 byt.. 下一篇python list生成表达式

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目