python - sys.getrefcount 继续

标签 python del

link text

我得到了引用计数的概念

所以当我执行“del astrd”时,引用计数降为零并且 astrd 被 gc 收集?

这是示例代码。这些代码是我在昨天的问题之后开发的:link text

一个.py:

def abc():

print "Hello"
print "123"
print '345'

二.py:

import one
#reload(one)

#def defg():

one.abc()

三.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)

我在 three.py 中所做的是否正确? 是否有任何不必要的步骤?如果是,为什么?

请帮我解决这个问题。

最佳答案

我相信当引用计数达到零时,内存会自动释放。 GC 不参与。

python GC是可选的,只有在存在引用循环不可达的对象时才使用。事实上,如果您确定您的程序不会创建引用循环,您可以调用 gc.disable()

至于原来的问题:

  • 当您执行 del astrd 时,您从本地命名空间中删除了 astrd 的绑定(bind)一个对象的引用(无论 astrd 引用是什么)。
  • 如果这意味着引用计数为零,则对象使用的内存被释放。
  • 所以 del 不会删除对象,它会取消绑定(bind)引用。如果取消绑定(bind)引用导致引用计数达到零,则会发生对象删除。

请注意,以上仅适用于 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.

关于python - sys.getrefcount 继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/759906/

相关文章:

python - 如何编译 Python 1.0

python - SWIG fatal error C1083 : Cannot open include file

python - 在 Python 中,使用 `del` 语句是代码异味吗?

javascript - 在 Laravel Mix 中删除临时文件

如果变量存在于列表中,则从 self 中删除变量的 Pythonic 方法

python - 如何使用 POST 方法自动进行网站交互

python - 如何从 python 代码调用 shell 脚本?

python - 将一个类标记为抽象类而不定义任何抽象方法

python - 在 python 中从列表中删除类实例有困难