在 python 中,变量与数据是分开存储的,数据保存在内存中的一个位置,变量中保存着数据在内存中的地址,即变量中是记录着数据的地址。
如果变量已经被定义,当给变量赋值时,本质上时修改了数据的引用地址。
在 python 中,参数的实参/返回值 都是靠引用来传递
def test(num): print("-" * 50) print("%d 在函数内的内存地址是 %x" % (num, id(num))) result = 100 print("返回值 %d 在内存中的地址是 %x" % (result, id(result))) print("-" * 50) return result a = 10 print("调用函数前 内存地址是 %x" % id(a)) r = test(a) print("调用函数后 实参内存地址是 %x" % id(a)) print("调用函数后 返回值内存地址是 %x" % id(r)) 调用函数前 内存地址是 a67be0 -------------------------------------------------- 10 在函数内的内存地址是 a67be0 返回值 100 在内存中的地址是 a68720 -------------------------------------------------- 调用函数后 实参内存地址是 a67be0 调用函数后 返回值内存地址是 a68720
可变类型数据的变化,实际上是通过 方法 来实现的。
原文:https://www.cnblogs.com/chan-shi/p/10565063.html