gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:42:26 25 4
gpt4 key购买 nike

我正在开发一个 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 })

我的问题是,当我创建删除/删除方法并想要从 all_repos 字典中清除 Repository 实例时,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

最佳答案

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

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

关于python - Python 如何/何时垃圾收集包含所有自身类型集合的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20253155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com