1

I actually have a question on Python3. I want to save the attributes of a class in a file, when the destructor is called. How can I do that?

I tried to do it like this:

def __del__:
   file = open("test.dat", "w")
   file.write("Hello")
   file.close()

That code doesn't work. I've already read, that you shouldn't use it, but I actually didn't find a alternative which works. Can anybody help me?

Thanks in advance!

  • What is the use case for this? When exactly are you expecting data to be saved? – Daniel Roseman May 11 '17 at 09:50
  • Well, the thing is I need to save some attributes of the class, because I need some of the attributes, when I start the python script again. Therefore I need to save the old data in file and read the from the while, when I start to create the class again. – Blacktiger800 May 11 '17 at 09:58

1 Answers1

0

to use that code it needs to be part of a class:

class Test():
    def __init__(self):
        self.data = "Hello"

    def __del__(self):
        with open('text.txt', mode='w') as file:
            file.write(self.data)

if __name__ == '__main__':
    def something():
        obj = Test() # obj is deleted when function exits as it becomes out of scope
    something()

    obj = Test()
    del obj # also works because we explicitly delete the object

note that while this method does work, it cannot always be relied upon to always be executed, for example if a sys.exit is called

James Kent
  • 5,763
  • 26
  • 50
  • At first, thanks for the answer. When I do this, I always get the error: NameError: name 'open' is not defined – Blacktiger800 May 11 '17 at 10:13
  • 1
    just had a look, are you using a version later than 3.4 (eg 3.5 or 3.6?) if so: http://stackoverflow.com/a/29737870/3185884 – James Kent May 11 '17 at 10:21