关于python的深拷贝和浅拷贝

时间:2021-08-24 22:27:07

写类函数的时候出了一个错,原代码写在这里:

def Update(self, wm, vm, ts, pos, vn, att):
        # 上一时刻位置,速度
        pos_pre = pos
     self.pos = pos vn_pre
= vn
     self.vn = vn
# vn更新 self.vn = self.vn + self.delta_vn # pos更新 self.pos[0, 0], self.pos[1, 0] = Q2Pos(self.qne) self.pos[2, 0] = self.pos[2, 0] - mid_vn[2, 0] * ts

这样写的时候,pos_pre会随着self.pos的改变而改变,vn_pre不会随着self.vn改变。

原因:在开辟空间时,同时将pos_pre和self.pos指向pos,将vn_pre和self.vn指向vn,但在修改vn时,是重建数组,即重新创建了一个数据空间,但在修改pos时,是在原数组空间进行修改。

举个例子:

In [2]: a = [1,2,3]

In [3]: def test(a):
   ...:     c = a
   ...:     d = a
   ...:     d = [2,3,4]
   ...:     return c
   ...:

In [4]: test(a)
Out[4]: [1, 2, 3]

In [6]: def test2(a):
   ...:     c = a
   ...:     d = a
   ...:     d[0] = 5
   ...:     return c
   ...:

In [7]: test2(a)
Out[7]: [5, 2, 3]

如果实现空间独立,使用深拷贝,每个数组开辟一个新的空间:

In [1]: import copy

In [2]: a = [1,2,3]

In [3]: def test3(a):
   ...:     c = copy.deepcopy(a)
   ...:     d = copy.deepcopy(a)
   ...:     d[0] = 5
   ...:     return c
   ...:

In [4]: test3(a)
Out[4]: [1, 2, 3]