同一个对象的值被不断修改,但内存地址没有改变的结果:
-
$cat test01.py
-
#!/usr/bin/python
-
#-*- encoding: utf-8 -*-
-
mylist=[]
-
a={}
-
for i in range(1,5):
-
# 注意这个 a={},如果只在上面初始化一次,就等于是同一个对象的内容不断擦除重写,但内存地址不会改变
-
#a={}
-
a["name"]='myname_'+str(i)
-
print a
-
print id(a)
-
mylist.append(a)
-
print '------------------'
-
print mylist
-
-
$python test01.py
-
{'name': 'myname_1'}
-
35410624
-
{'name': 'myname_2'}
-
35410624
-
{'name': 'myname_3'}
-
35410624
-
{'name': 'myname_4'}
-
35410624
-
------------------
-
[{'name': 'myname_4'}, {'name': 'myname_4'}, {'name': 'myname_4'}, {'name': 'myname_4'}]
每次在修改对象值的时候,重新初始化新的内存地址:
-
$cat test02.py
-
#!/usr/bin/python
-
#-*- encoding: utf-8 -*-
-
mylist=[]
-
#a={}
-
for i in range(1,5):
-
# 注意这个 a={},如果只在上面初始化一次,就等于是同一个对象的内容不断擦除重写,但内存地址不会改变
-
a={}
-
a["name"]='myname_'+str(i)
-
print a
-
print id(a)
-
mylist.append(a)
-
print '------------------'
-
print mylist
-
-
-
$python test02.py
-
{'name': 'myname_1'}
-
22143680
-
{'name': 'myname_2'}
-
22212272
-
{'name': 'myname_3'}
-
22143104
-
{'name': 'myname_4'}
-
22211984
-
------------------
-
[{'name': 'myname_1'}, {'name': 'myname_2'}, {'name': 'myname_3'}, {'name': 'myname_4'}]
阅读(1007) | 评论(0) | 转发(0) |