Suppose there is a program with a couple of objects living in it at runtime.
Is the __del__ method of each object called when the programs ends?
If yes I could for example do something like this:
class Client:__del__( self ):disconnect_from_server()
Suppose there is a program with a couple of objects living in it at runtime.
Is the __del__ method of each object called when the programs ends?
If yes I could for example do something like this:
class Client:__del__( self ):disconnect_from_server()
There are many potential difficulties associated with using __del__
.
Usually, it is not necessary, or the best idea to define it yourself.
Instead, if you want an object that cleans up after itself upon exit or an exception, use a context manager:
per Carl's comment:
class Client:def __exit__(self,ext_type,exc_value,traceback):self.disconnect_from_server()with Client() as c:...
original answer:
import contextlibclass Client:...@contextlib.contextmanager
def make_client():c=Client()yield cc.disconnect_from_server()with make_client() as c:...