Python中的copy与deepcopy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
In [1]: import copy
In [2]: a = [1, 2, 3]
In [3]: b = [4 ,5 ,6]
In [4]: c = [a, b]
In [5]: d = copy.copy(c)
In [6]: id(c)
Out[6]: 4578276616
In [7]: id(d)
Out[7]: 4578334600
In [8]: id(c[0])
Out[8]: 4578509768
In [9]: id(d[0])
Out[9]: 4578509768
In [10]: e = copy.deepcopy(c)
In [11]: id(e)
Out[11]: 4578533704
In [12]: id(e[0])
Out[12]: 4578477576

copy/deepcopy方法作用于不可变数据类型:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
In [1]: import copy
In [2]: a = (1, 2, 3)
In [3]: b = (4, 5, 6)
In [4]: c = (a, b)
In [5]: d = copy.copy(c)
In [6]: id(c)
Out[6]: 4414753736
In [7]: id(d)
Out[7]: 4414753736
In [8]: e = copy.deepcopy(c)
In [9]: id(e)
Out[9]: 4414753736
In [10]: id(c[0])
Out[10]: 4377084768
In [11]: id(d[0])
Out[11]: 4377084768
In [12]: id(e[0])
Out[12]: 4377084768

总结:

  1. a = b,a和b指向同一内存地址。
  2. deepcopy 深拷贝,递归拷贝内部所有值,全部开辟新的内存地址。
  3. copy可变类型(比如list),最外层开辟新的内存地址,内部的值不开辟新的内存地址4. copy不可变类型(比如tuple),最外层不开辟新的内存地址。

Python多继承子类的方法溯源规则

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class A():
def __init__(self):
pass
def save(self):
print "This is from A"
class B(A):
def __init__(self):
pass
class C(A):
def __init__(self):
pass
def save(self):
print "This is from C"
class D(B,C):
def __init__(self):
pass
test = D()
test.save()

经典类的答案: This is from A

新式类的答案: This is from C