python中可变与不可变类型

可变类型之陷阱:永远不要使用可变对象作为默认参数(因为它可变)
案例一:

def fo(a, b, c=[]):
    c.append(a)
    c.append(b)
    print(c)

fo(1, 1)
fo(1, 1)
fo(1, 1)
# 运行结果:
[1, 1]
[1, 1, 1, 1]
[1, 1, 1, 1, 1, 1]

案例二:

def extendlist(val, list=[]):
    list.append(val)
    return list

list1 = extendlist(20)
list2 = extendlist(345, [])
list3 = extendlist('abs')

print("list1 = %s" %list1)
print("list2 = %s" %list2)
print("list3 = %s" %list3)
# 运行结果:
list1 = [20, 'abs']
list2 = [345]
list3 = [20, 'abs']

猜你喜欢

转载自blog.csdn.net/weixin_43269166/article/details/87702565