Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Can';t在任何类中从析构函数调用函数_Python - Fatal编程技术网

Python Can';t在任何类中从析构函数调用函数

Python Can';t在任何类中从析构函数调用函数,python,Python,我想在一个类中使用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=

我想在一个类中使用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()
如果函数名为
test1
test2
test3
,将引发异常,我无法通过
try except
捕获它

回溯是:

E:\tc.py
Exception TypeError: "'NoneType' object is not callable" in <bound method Class1.__del__ of <__main__.Class1 instance at 0x00C18F58>> ignored
E:\tc.py
异常类型错误:忽略中的“非类型”对象不可调用

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

你不能确定
test3
在调用
obj.\uu del\uuuu()
时没有被破坏。在
Class1中添加对它的引用。\uuuu init\uuuu()
如果需要保留它。

对象的销毁顺序未定义。这意味着当调用
obj.\uu del\uu()
时——如果调用了它——
test3()
可能已被销毁,也可能未被销毁

屏幕上有一个带有警告的红色框:

警告由于调用
\uuu del\uuu()
方法的不稳定情况,在执行过程中发生的异常将被忽略,并将警告打印到
sys.stderr
此外,当调用
\uu del\uuuuuuuuuuuuuuu()
以响应被删除的模块时(例如,当程序执行完成时),由
\uuuu del\uuuuuuuuuuuuuuuu()
方法引用的其他全局变量可能已经被删除或正在被拆除(例如,导入机器关闭)
。出于这个原因,
\uu del\uu()
方法应该尽可能少地维护外部不变量。从版本1.5开始,Python保证在删除其他全局变量之前,从其模块中删除名称以单个下划线开头的全局变量;如果不存在对此类全局变量的其他引用,这可能有助于确保导入的模块在调用
\uu del\uu()
方法时仍然可用


在Python中,几乎从不重写
\uu del\uu
。你可能应该重新考虑你的设计。请看

这是一个完美的答案。我以前在析构函数中保存工作,就像C++一样。Python中的错误,我得到这个红色框。@魏明珍:没错,Python的 -DELYLY比Java的终结器更类似于C++析构函数。在现代Python中,
with
语句是释放资源的正确习惯用法(
try
-
finally
是一个遥远的秒)。