gpt4 book ai didi

python - 无法从任何类中的析构函数调用函数

转载 作者:行者123 更新时间:2023-11-28 19:45:21 25 4
gpt4 key购买 nike

我想在一个类中使用 ConfigParser,它需要从析构函数中调用,但奇怪的事情发生了。

这是我的代码:

"""
function name is
test ok!
test1 failed!
test2 failed!
test3 failed!

test4
... ok!

"""

def test3():
pass

class Class1:
def __del__(self):
test3()

if __name__=="__main__":
obj=Class1()

如果函数名为test1test2test3,将引发异常,我无法通过尝试除外

回溯是:

E:\tc.py
Exception TypeError: "'NoneType' object is not callable" in <bound method Class1.__del__ of <__main__.Class1 instance at 0x00C18F58>> ignored

太奇怪了!你能在你的系统中测试它吗?还是我做错了什么?

最佳答案

对象被销毁的顺序是未定义的。这意味着当 obj.__del__() 被调用时——如果它被调用的话——test3() 可能已经被破坏也可能没有被破坏。

documentation中有一个带有警告的红框:

Warning Due to the precarious circumstances under which __del__() methods are invoked, exceptions that occur during their execution are ignored, and a warning is printed to sys.stderr instead. Also, when __del__() is invoked in response to a module being deleted (e.g., when execution of the program is done), other globals referenced by the __del__() method may already have been deleted or in the process of being torn down (e.g. the import machinery shutting down). For this reason, __del__() methods should do the absolute minimum needed to maintain external invariants. Starting with version 1.5, Python guarantees that globals whose name begins with a single underscore are deleted from their module before other globals are deleted; if no other references to such globals exist, this may help in assuring that imported modules are still available at the time when the __del__() method is called.

在 Python 中,几乎从不覆盖 __del__。您可能应该重新考虑您的设计。参见 How do I correctly clean up a Python object?

关于python - 无法从任何类中的析构函数调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10811681/

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