1.小整数[-5.257)、单个单词、单个字符公用对象。大整数,含空格的字符串不公用内存,引用计数为0,对象被销毁。
>>> a = 999
>>> b=999
>>> a is b
False
>>> a=20
>>> b=20
>>> a is b
True
>>> a='test'
>>> b='test'
>>> a is b
True
>>> a='test hello get'
>>> b='test hello get'
>>> a is b
False
>>> a==b
True
>>> a='a'
>>> b='a'
>>> a is b
True
>>> a==b
True
2. python采用的是引用计数机制为主,标记-清除和分代收集两种机制为辅的垃圾回收策略。
垃圾回收器的主要任务:为新生对象分配内存,识别垃圾对象并将其回收。
出发垃圾回收的情况:1.调用gc.collect() 2.当gc模块的计数器到达阀值 3.程序退出
查看对象的引用计数:
import sys
a='test'
print(sys.getrefcount(a))
引用计数机制的一大缺陷是循环引用:t1对象和t2对象互相引用对方,导致引用计数永远大于0。
class Test(object):
#用于测试垃圾回收的测试类
def __init__(self):
print("Test对象被创建。。。。")
if __name__=='__main__':
#循环引用的例子
t1 = Test()
t2 = Test()
t1.t = t2
t2.t = t1
显示调用垃圾回收的例子:
import gc
class Test(object):
#用于测试垃圾回收的测试类
def __init__(self):
print("Test对象被创建。。。。")
def testgc():
t1=Test()
t2=Test()
t1.t=t2
t2.t=t1
del t1
del t2
t3 = Test()
del t3
print('----准备垃圾回收-----')
print(gc.garbage)
print('--------垃圾回收--------')
print(gc.collect())
print('------查看垃圾回收结果-----')
print(gc.garbage)
if __name__=='__main__':
gc.set_debug(gc.DEBUG_LEAK)
testgc()
运行结果:
Test对象被创建。。。。
Test对象被创建。。。。
Test对象被创建。。。。
----准备垃圾回收-----
[]
--------垃圾回收--------
4
------查看垃圾回收结果-----
[<__main__.Test object at 0x013EA530>, <__main__.Test object at 0x013EA590>, {'t': <__main__.Test object at 0x013EA590>}, {'t': <__main__.Test object at 0x013EA530>}]
3. gc不能处理的循环引用的情况,当类本身重写了__del__方法的时候
import gc
class Test(object):
#用于测试垃圾回收的测试类
def __init__(self):
print("Test对象被创建。。。。")
def __del__(self):
print("------del------")
def testgc():
t1=Test()
t2=Test()
t1.t=t2
t2.t=t1
del t1
del t2
t3 = Test()
del t3
print('----准备垃圾回收-----')
print(gc.garbage)
print('--------垃圾回收--------')
print(gc.collect())
print('------查看垃圾回收结果-----')
print(gc.garbage)
if __name__=='__main__':
gc.set_debug(gc.DEBUG_LEAK)
testgc()
运行结果:
gc: collectable <Test 0x0255A530>
Test对象被创建。。。。
gc: collectable <Test 0x0255A590>
Test对象被创建。。。。
gc: collectable <dict 0x0255D0C0>
Test对象被创建。。。。
gc: collectable <dict 0x025FF8D0>
------del------
----准备垃圾回收-----
[]
--------垃圾回收--------
------del------
------del------
4
------查看垃圾回收结果-----
[<__main__.Test object at 0x0255A530>, <__main__.Test object at 0x0255A590>, {'t': <__main__.Test object at 0x0255A590>}, {'t': <__main__.Test object at 0x0255A530>}]