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 to make a response on the web using MQTT and Flask?
Four-of-a-Kind Dice Game
Python subprocess - how to redirect only input
Calculation Server Architecture
PyAutoGui crashes when if/then statements are included
Disallowed Host at Django
Cannot import PyQtGraph because packages PySide, PyQt4, or PyQt5 can't be imported?
BeautifulSoup4 not working on my hosting server
Argument parser error: too few arguments
from .forms import RegisterForm error
How to automate grabcut algorithm in opencv python?
2-dimensional binning with Pandas
how to get the differences in a list
I need this squares to 'fall' or be positioned lower when there's nothing under them
Python: Extract XML texts except under certain tags
Using functions in different files