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

2024-05-15 10:35:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在研究一个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 })

我的问题是,在python中创建delete/remove方法并希望从all_repos字典中清除Repository的实例时会发生什么?下面是我计划用的方法:

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


Tags: thenameinself字典objectrepositoryrepo