defchange(b): print("b's id before change:{}".format(id(b))) b = b + 1 print("b's id after change:{}".format(id(b))) a = 2 print("a's id before function:{}".format(id(a))) change(a) print("a's id after function:{}".format(id(a)))
1 2 3 4
a's id before function:94804014773312 b's id before change:94804014773312 b's id after change:94804014773344 a's id after function:94804014773312
可以看出,在函数传值的时候,传的也是引用,只不过在对不可变对象进行改变的时候会建立新的副本
string类型
1 2 3 4 5 6 7 8
a = 'value' b = a c = 'value' print(id(a),id(b),id(c)) b = b + '1' c = c + '' print(a,b,c) print(id(a),id(b),id(c))
1 2 3
139906629646072 139906629646072 139906629646072 value value1 value 139906629646072 139906483630008 139906629646072
string类型在进行操作的时候特性和int一致,函数引用就不再举例了
tuple类型
1 2 3 4 5 6 7 8
a = (1,2,3) b = a c = (1,2,3) print(id(a),id(b),id(c)) b = b + (4,) c = c + () print(a,b,c) print(id(a),id(b),id(c))
defchange(b): print("b's id before change:{}".format(id(b))) b[0] = 4 print("b's id after change:{}".format(id(b))) a = [1,2,3] print("a's id before function:{}".format(id(a))) change(a) print("a's id after function:{}".format(id(a)))
1 2 3 4
a's id before function:139906492315784 b's id before change:139906492315784 b's id after change:139906492315784 a's id after function:139906492315784
在函数传递的时候传的也是引用
如何为list类型变量建立新的副本
1 2 3 4 5 6
a = [1,2,3] print(id(a)) b = a[:] print(id(b)) c = a.copy() print(id(c))
1 2 3
139906483601608 139906492315784 139906501528840
通过以上两种方式就可以为list建立新的副本
有趣的操作
1 2 3 4 5 6 7 8
a = [1,2,3] print(id(a)) a = a + [4] print(a) print(id(a)) a += [5] print(a) print(id(a))