我得到了引用计数的概念
所以,当我执行"del astrd"时,引用计数降为零,astrd被gc收集?
这是示例代码.这些代码是我在昨天的问题之后开发的:链接文本
one.py:
def abc():
print "Hello"
print "123"
print '345'
Run Code Online (Sandbox Code Playgroud)
two.py:
import one
#reload(one)
#def defg():
one.abc()
Run Code Online (Sandbox Code Playgroud)
three.py:
import os,sys,gc
from time import sleep
import two
#reload(two)
#two.defg()
sleep(20)
directory = os.listdir('.')
for filename in directory:
if filename[-3:] == 'pyc':
print '- ' + filename
print sys.getrefcount(filename)
file_name = os.path.splitext (filename)[0]
del file_name # remove the local reference
del sys.modules[os.path.splitext (filename)[0]] # removes import
gc.collect() # garbage collect
#del sys.modules[filename]
#del filename
#os.remove(filename)
Run Code Online (Sandbox Code Playgroud)
我在three.py中所做的是对还是不对?有没有必要的步骤?如果是,为什么?
请帮我解决这个问题.
我相信,当refcount达到零时,内存会自动释放.GC不涉及.
python GC是可选的,仅在存在具有引用周期的不可到达对象时使用.实际上,gc.disable()
如果您确定您的程序没有创建参考周期,则可以调用.
至于原来的问题:
del astrd
,将从本地名称空间中删除astrd绑定对对象的引用(无论是什么astrd引用).del
不删除对象,它取消绑定引用.如果取消绑定引用导致引用计数达到零,则删除对象会产生副作用.请注意,以上仅适用于CPython.Jython和IronPython使用JVM/CLR GC机制,并且根本不使用引用计数,我相信.
方便的gc.get_objects
返回python解释器跟踪的所有对象实例的列表.例:
import gc class test(object): pass def number_of_test_instances(): return len([obj for obj in gc.get_objects() if isinstance(obj, test)]) for i in range(100): t = test() print "Created and abandoned 100 instances, there are now", \ number_of_test_instances(), \ "instances known to the python interpreter." # note that in normal operation, the GC would # detect the unreachable objects and start # collecting them right away gc.disable() for i in range(100): t = test() t.t = t print "Created and abandoned 100 instances with circular ref, there are now", \ number_of_test_instances(), \ "instances known to the python interpreter." gc.collect() print "After manually doing gc.collect(), there are now", \ number_of_test_instances(), \ "instances known to the python interpreter."
运行此程序给出:
Created and abandoned 100 instances, there are now 1 instances known to the python interpreter. Created and abandoned 100 instances with circular ref, there are now 100 instances known to the python interpreter. After manually doing gc.collect(), there are now 1 instances known to the python interpreter.
归档时间: |
|
查看次数: |
1727 次 |
最近记录: |