2013-11-27 38 views
1

我正在研究一個類似於此答案中的示例的Python類:https://stackoverflow.com/a/1383744/576333。該類本身使用字典跟蹤所有創建的對象。Python垃圾如何收集包含所有類型集合的對象?

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 }) 

我的問題是,當我創建一個刪除/刪除方法,並希望從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

+0

當'了'和'Repository.all_repos'分離,它像任何其他對象,因此它*可*垃圾當最後一次引用消失時收集。不過,它不需要。 –

+0

http://stackoverflow.com/questions/4484167/details-how-python-garbage-collection-works –

回答