删除对对象的引用,但如果在其他地方引用,则将对象保留在内存中

Delete reference to object but keep object in memory if referenced elsewhere

我遇到的问题: 一个函数接收对对象的引用,并在其例程的某个时间点对这些引用调用 del。

这些引用引用的对象有时在别处引用,有时不引用。

我希望 del 语句只删除函数中存在的引用。如果该对象在程序的其他地方没有被引用,它就会被垃圾回收。 如果我是正确的,del 直接调用对象的析构函数而不是简单地删除它的引用。 我怎样才能得到想要的行为?

If i'm correct, del directly calls the destructor of object rather than simply delete its reference.

假设是 CPython,这是不正确的。

del 将对象的引用计数减 1。当引用计数达到 0 时,对象将被垃圾回收。

如果 析构函数 你指的是 __del__ 魔术方法,请注意它 通常 在对象被调用时调用垃圾收集,而不是在调用 del 时。而且,there's no guarantee that the method would even be called.

请注意,还有一个(可选的)gc 接口可以打破对象引用循环。