先看一段代码
if __name__ == '__main__':
tx1 = {'from': 'Jason', 'to': 'Karmen'}
tx2 = {'from': 'Jason', 'to': 'Karmen'}
# id(txs[0]) = id(tx1) & id(txs[1]) = id(tx2)
txs = [tx1, tx2]
# [{'to': 'Karmen', 'from': 'Jason'}, {'to': 'Karmen', 'from': 'Jason'}]
print txs
# 往tx1新增一个键,txs也会更新
tx1['?'] = '?'
tx1['from'] = 'God'
# [{'to': 'Karmen', 'from': 'God', '?': '?'}, {'to': 'Karmen', 'from': 'Jason'}]
print txs
mylist = []
# id(mylist[0]) = id(tx1)
mylist.append(tx1)
mylist[0]['from'] = 'SKY'
# [{'to': 'Karmen', 'from': 'SKY', '?': '?'}, {'to': 'Karmen', 'from': 'Jason'}]
print txs
# [{'to': 'Karmen', 'from': 'SKY', '?': '?'}]
print mylist
# id(mylist[0]) = id(mylist[1]) = id(tx1)
mylist.append(tx1)
mylist[1]['to'] = 'RAINBOW'
# [{'to': 'RAINBOW', 'from': 'SKY', '?': '?'}, {'to': 'Karmen', 'from': 'Jason'}]
print txs
# [{'to': 'RAINBOW', 'from': 'SKY', '?': '?'}, {'to': 'RAINBOW', 'from': 'SKY', '?': '?'}]
print mylist
结果为:
[{'to': 'Karmen', 'from': 'Jason'}, {'to': 'Karmen', 'from': 'Jason'}]
[{'to': 'Karmen', 'from': 'God', '?': '?'}, {'to': 'Karmen', 'from': 'Jason'}]
[{'to': 'Karmen', 'from': 'SKY', '?': '?'}, {'to': 'Karmen', 'from': 'Jason'}]
[{'to': 'Karmen', 'from': 'SKY', '?': '?'}]
[{'to': 'RAINBOW', 'from': 'SKY', '?': '?'}, {'to': 'Karmen', 'from': 'Jason'}]
[{'to': 'RAINBOW', 'from': 'SKY', '?': '?'}, {'to': 'RAINBOW', 'from': 'SKY', '?': '?'}]
先看一段代码
def f(x,l=[]):
for i in range(x):
l.append(i*i)
print(l)
print('---1---')
f(4)
print('---2---')
f(5)
执行结果:
---1---
[0, 1, 4, 9]
---2---
[0, 1, 4, 9, 0, 1, 4, 9, 16]
预期的结果为:
---1---
[0, 1, 4, 9]
---2---
[0, 1, 4, 9, 16]
当定义函数时,会保存函数中默认参数list的值,即保存list的id。
def f(x,l=None):
if l is None:
l = []
for i in range(x):
l.append(i*i)
print(l)
print('---1---')
f(4)
print('---2---')
f(5)
print('---3---')
f(6)
结果:
---1---
[0, 1, 4, 9]
---2---
[0, 1, 4, 9, 16]
---3---
[0, 1, 4, 9, 16, 25]