In addition to the above answers to exemplify invocation order, a simple run example
class myclass:
def __init__(self):
print("__init__")
def __enter__(self):
print("__enter__")
def __exit__(self, type, value, traceback):
print("__exit__")
def __del__(self):
print("__del__")
with myclass():
print("body")
Produces the output:
__init__
__enter__
body
__exit__
__del__
A reminder: when using the syntax with myclass() as mc
, variable mc gets the value returned by __enter__()
, in the above case None
! For such use, need to define return value, such as:
def __enter__(self):
print('__enter__')
return self