如何/何时Python垃圾收集包含所有类型集合的对象?

时间:2013-11-27 21:11:34

标签: python oop python-collections

我正在开发一个Python类,其结构类似于这个答案中的示例:https://stackoverflow.com/a/1383744/576333。类本身使用字典跟踪所有创建的对象。

class Repository(object):

    # All repositories are stored in this class-level dictionary such that 
    # all instances of this class maintain the same set.
    all_repos = {}   

    def __init__(self, name, data):
        """
        Create a repository object. If it has the required tags, include it in
        the collection of all repositories.
        """

        # Don't add it if it already exists
        if not name in Repository.all_repos:

            # Store the attributes
            self.__dict__ = data
            self.__dict__['name'] = name

            Repository.all_repos.update({ name: self })

我的问题是当我创建一个删除/删除方法并想要从Repository字典中清除all_repos的实例时,python会发生什么?以下是我计划做这样的方法:

def remove(self):
    repo = Repository.all_repos.pop(self.name) # pop it out
    print "You just removed %s" % repo.name

具有以下用途:

a= Repository('repo_name', {'attr1':'attr1_value',...}
a.remove()

此时,a仍然存在,但不在Repository.all_repos中。 Python什么时候会删除a

1 个答案:

答案 0 :(得分:1)

我发现这篇文章对于可视化垃圾收集非常有帮助。它使用Ruby的GC进行比较,但值得阅读:

http://patshaughnessy.net/2013/10/24/visualizing-garbage-collection-in-ruby-and-python