python 可变对象导致的坑

Python中一切都是对象,对外表现是传地址, tuple,string,number是不可变对象,也就是内存分配后,内存内 存的值不再改变.
Python中 list和dict是可变对象, 可以append和pop, 所以就有了坑,

深拷贝浅拷贝:

1
2
3
4
5
6
7
8
9
10
a = 1
def fun(a):
a = 2
fun(a)
print a # 1
a = []
def fun(a):
a.append(1)
fun(a)
print a # [1]

函数参数默认值 :

1
2
3
4
5
6
7
8
9
10
11
>>> def generate_new_list_with(my_list=[], element=None):
... my_list.append(element)
... return my_list
...
>>> list_1 = generate_new_list_with(element=1)
>>> list_1
[1]
>>> list_2 = generate_new_list_with(element=2)
>>> list_2
[1, 2]
>>>