Python作为现代最易用的编程语言之一,常常令使用者忘记引用管理(指针),内存管理,对象回收的问题。
本人在使用Python的过程中遇到的最浅显的问题:List列表和Dict字典等作为函数参数传入,在函数调用后可以一同改变内部数值,而单一的数值则无法随同函数调用一同改变。
参考该博文python对象和垃圾回收
Number测试
本人先对数值做了如下测试:
b = 1
print("b is referred %d"% sys.getrefcount(b))
c = b
print("c is referred %d"% sys.getrefcount(c))
a = c
if c is b:
print("c is b")
pass
if a is b:
print("a is b")
pass
print("a is referred %d"% sys.getrefcount(a))
print("b is referred %d"% sys.getrefcount(b))
print("c is referred %d"% sys.getrefcount(c))
输出结果:
b is referred 132
c is referred 133
c is b
a is b
a is referred 134
b is referred 134
c is referred 134
证明:计数器对于b=1这个对象又新增了2两个引用
当改变c或b时:
c += 1
print("a is %d" % a)
print("b is %d" % b)
print("c is %d" % c)
print("a is referred %d"% sys.getrefcount(a))
print("b is referred %d"% sys.getrefcount(b))
print("c is referred %d"% sys.getrefcount(c))
if a is b:
print("a is b")
pass
if a is c:
print("a is c")
pass
b = 2
print("a is %d" % a)
print("b is %d" % b)
print("c is %d" % c)
if a is b:
print("a is b")
pass
if a is c:
print("a is c")
pass
print("b is referred %d"% sys.getrefcount(b))
print("c is referred %d"% sys.getrefcount(c))
print("a is referred %d"% sys.getrefcount(a))
输出为:
a is 1
b is 1
c is 2
a is referred 133
b is referred 133
c is referred 97
a is b
a is 1
b is 2
c is 2
b is referred 98
c is referred 98
a is referred 132
证明:当Number类型引用链的任意一个环节数值被修改时,则会自动将引用指向数值为被修改值的对象
使用getrefcount测试回收机制
真厉..h..还没测呢...还没测...