【发布时间】:2020-11-29 21:47:13
【问题描述】:
我有一个单例类,但我不明白 Python 垃圾收集器如何不删除实例。
我正在使用 - from singleton_decorator import singleton
我班的例子:
from singleton_decorator import singleton
@singleton
class FilesRetriever:
def __init__(self, testing_mode: bool = False):
self.testing_mode = testing_mode
测试示例:
def test_singletone(self):
FilesRetriever(testing_mode=True)
mode = FilesRetriever().testing_mode
print("mode 1:" + str(mode))
mode = FilesRetriever().testing_mode
print("mode 2:" + str(mode))
count_before = gc.get_count()
gc.collect()
count_after = gc.get_count()
mode = FilesRetriever().testing_mode
print("mode 3:" + str(mode))
print("count_before:" + str(count_before))
print("count_after:" + str(count_after))
测试输出:
mode 1:True
mode 2:True
mode 3:True
count_before:(306, 10, 5)
count_after:(0, 0, 0)
我希望在垃圾收集器自动运行或在我的测试中运行它之后,_SingletonWrapper 的实例(装饰器实现中的类)将被删除,因为没有任何东西指向它。然后 "print("mode 3:" + str(mode))" 的值将为 False,因为这是默认值(并且重新创建了实例)
【问题讨论】:
标签: python memory garbage-collection