在C语言里,普通变量进行赋值,赋的是值,数组赋值,赋的是地址
eg
int a = 10;
int b = a;
==>a=b=10
a = 20;
==>a=20≠b=10
char c[10] = "apple";
char *d = c;
==>c=d->"apple"
c[0] = 'b';
==>c=d=>"bpple"
在Python中,分为可变变量和不可变变量,传递的都是地址,但是,可变变量的修改会对原始数据造成修改,不可变变量则不会。
>>> a = 1
>>> b = a
>>> id(a)
140551545594848
>>> id(b)
140551545594848
>>> a = 2
>>> a
2
>>> b
1
>>> id(a)
140551545594880
>>> id(b)
140551545594848
>>> a = ['1','2']
>>> b = a
>>> b == a
True
>>> a[0] = 0
>>> a
[0, '2']
>>> b
[0, '2']
>>> id(a) == id(b)
True
看一段代码
def fuzhi():
a = [1,['s','z']]
b = a
print('a=%s,id(a)=%d,id(a[i])={%s}'%(a,id(a),[id(i) for i in a]))
print('b=%s,id(b)=%d,id(b[i])={%s}'%(b,id(b),[id(i) for i in b]))
a[0] = 2
a[1].append('x')
print('do some change on a...')
print('a=%s,id(a)=%d,id(a[i])={%s}' % (a, id(a), [id(i) for i in a]))
print('b=%s,id(b)=%d,id(b[i])={%s}' % (b, id(b), [id(i) for i in b]))
结果
a=[1, ['s', 'z']],id(a)=139889808571848,id(a[i])={[139889944073184, 139889808571912]}
b=[1, ['s', 'z']],id(b)=139889808571848,id(b[i])={[139889944073184, 139889808571912]}
do some change on a...
a=[2, ['s', 'z', 'x']],id(a)=139889808571848,id(a[i])={[139889944073216, 139889808571912]}
b=[2, ['s', 'z', 'x']],id(b)=139889808571848,id(b[i])={[139889944073216, 139889808571912]}
得到结论:
亦称浅拷贝
见代码:
def ShallowCopy():
a = [1,['s','z']]
b = copy.copy(a)
print('a=%s,id(a)=%d,id(a[i])={%s}' % (a, id(a), [id(i) for i in a]))
print('b=%s,id(b)=%d,id(b[i])={%s}' % (b, id(b), [id(i) for i in b]))
a[0] = 2
a[1].append('x')
print('do some change on a...')
print('a=%s,id(a)=%d,id(a[i])={%s}' % (a, id(a), [id(i) for i in a]))
print('b=%s,id(b)=%d,id(b[i])={%s}' % (b, id(b), [id(i) for i in b]))
结果:
a=[1, ['s', 'z']],id(a)=139769512091080,id(a[i])={[139769647592416, 139769512091144]}
b=[1, ['s', 'z']],id(b)=139769512090952,id(b[i])={[139769647592416, 139769512091144]}
do some change on a...
a=[2, ['s', 'z', 'x']],id(a)=139769512091080,id(a[i])={[139769647592448, 139769512091144]}
b=[1, ['s', 'z', 'x']],id(b)=139769512090952,id(b[i])={[139769647592416, 139769512091144]}
得到结论:
def DeepCopy():
a = [1, ['s', 'z']]
b = copy.deepcopy(a)
print('a=%s,id(a)=%d,id(a[i])={%s}' % (a, id(a), [id(i) for i in a]))
print('b=%s,id(b)=%d,id(b[i])={%s}' % (b, id(b), [id(i) for i in b]))
a[0] = 2
a[1].append('x')
print('do some change on a...')
print('a=%s,id(a)=%d,id(a[i])={%s}' % (a, id(a), [id(i) for i in a]))
print('b=%s,id(b)=%d,id(b[i])={%s}' % (b, id(b), [id(i) for i in b]))
a=[1, ['s', 'z']],id(a)=139764479819208,id(a[i])={[139764615320544, 139764479819272]}
b=[1, ['s', 'z']],id(b)=139764479819080,id(b[i])={[139764615320544, 139764479819016]}
do some change on a...
a=[2, ['s', 'z', 'x']],id(a)=139764479819208,id(a[i])={[139764615320576, 139764479819272]}
b=[1, ['s', 'z']],id(b)=139764479819080,id(b[i])={[139764615320544, 139764479819016]