Pickle 退出应用程序引发 AttributeError

Pickle on exiting application raises AttributeError

我试图在主应用程序关闭后 pickle class 实例,但我得到

Exception AttributeError: "'NoneType' object has no attribute 'dump'" in <bound method MainFrame.__del__ of <__main__.MainFrame object at 0x03BA6508>> ignored

这是一个示例代码:

from PySide.QtGui import *
import sys
import pickle

class Progress:
    def __init__(self, value):
        self.x = value

    def __del__(self):
        pickle.dump(self, open("pickle_file.p", "wb"))


class MainFrame(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        pass

    # def __del__(self):
    #     pickle.dump(progress, open("pickle_file.p", "wb"))

if __name__ == "__main__":
    try:
        with open("pickle_file.p", "r") as p_file:
            progress = pickle.load(p_file)
    except (EOFError, IOError):
        progress = Progress(1)

    app = QApplication(sys.argv)
    main = MainFrame()
    main.show()
    sys.exit(app.exec_())

__del__ 的两种方法都会引发相同的错误。

我该怎么做?

永远不要使用 __del__,除非你真的,真的知道你在做什么。

如果你想在退出时保存东西,重新实现主要的 closeEvent window:

class MainFrame(QWidget):
    ...

    def closeEvent(self, event):
        pickle.dump(progress, open("pickle_file.p", "wb"))