python对象的引用

1 利用 * 星号生成二维及二维以上的list时,特别要注意有的量引用是相同的.如果后面要给list赋值,最好不要这样生成list.

可以先这样生成,再打印输出后,粘贴到程序中重新赋值.

a = [['a'] * 3] * 3
print(a)
a[0][0]= 'b'
print(a)
# [['a', 'a', 'a'], ['a', 'a', 'a'], ['a', 'a', 'a']]
# [['b', 'a', 'a'], ['b', 'a', 'a'], ['b', 'a', 'a']]
View Code

参考:https://www.cnblogs.com/liaohuiqiang/p/9668303.html

2 append函数添加可变对象的时候也会出现类似的情况

person = {'name': '', 'id': 0}
team = []
for i in range(3):
    x = person
    x['id'] = i
    team.append(x)
    print(id(team[i]))
team[0]['name'] = 'Jack'
team[1]['name'] = 'Pony'
team[2]['name'] = 'Crossin'
print(team)
print(team[1])
# 140630417520392
# 140630417520392
# 140630417520392
# [{'name': 'Crossin', 'id': 2}, {'name': 'Crossin', 'id': 2}, {'name': 'Crossin', 'id': 2}]
# {'name': 'Crossin', 'id': 2}
View Code

 

posted on 2019-10-30 20:52  吃我一枪  阅读(206)  评论(0编辑  收藏  举报

导航