Python3: How to save data, when the destructor is called
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!
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
How do I display real-time python script output on a website?
how to extract some text by use lxml?
dynamically adding functions to a Python module
Scaling the y-axis with Matplotlib in Python
Shortening a oft-used code segment for testing a return value in Python
What is the best way to internationalize a Python app with multiple i18n domains?
IPv6 decoder for pcapy/impacket
Using paver and nose together with an atypical directory structure
Load an existing many-to-many table relation with sqlalchemy
How do I write this in Ruby/Python? Or, can you translate my LINQ to Ruby/Python?
Best Python templating library to facilitate code generation [closed]
Code samples for Django + SWFUpload?
CMake output name for dynamic-loaded library?
Python: undo write to file
Python: “1-2-3-4” to [1, 2, 3, 4]
Problem sub-classing BaseException in Python