gpt4 book ai didi

python - 覆盖 Python 析构函数 (__del__) 会导致内存泄漏吗?

转载 作者:行者123 更新时间:2023-12-05 06:56:31 30 4
gpt4 key购买 nike

我有一个脚本,我在其中使用 API 在云上创建一个对象,并希望在脚本末尾的某些情况下删除它。

class ObjCreator():
def __init__(self, keep_object: bool):
self.keep_object = keep_object
print("init")

def create_object(self):
print("Created object using API")

def delete_object(self):
print("Deleting object using API")

def __del__(self):
print("Deleting object using API only if keep_object is False")
if not self.keep_object:
self.delete_object()

我已经看到 Python 程序存在一些内存泄漏,因此显然 GC 并不完美(即无法收集的对象)。

我担心覆盖 del 函数会导致内存泄漏。那可能吗?如果是这样,您对不同的、优雅的解决方案有什么建议吗?

最佳答案

你的直觉是对的,覆盖 __del__ 方法意味着基类的 __del__ 方法不再自动调用(虽然我不不认为这里可能存在内存泄漏)。事实上文档 explicitly mentions this :

If a base class has a __del__() method, the derived class’s __del__() method, if any, must explicitly call it to ensure proper deletion of the base class part of the instance.

from the CPython repo 的代码示例:

    def __del__(self):
# ... your cleanup code here ...
super().__del__() # call to base class

关于python - 覆盖 Python 析构函数 (__del__) 会导致内存泄漏吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65108059/

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