I am trying to learn python and I landed on the
with..as
construct, that used like this:
with open("somefile.txt", 'rt') as file:
print(file.read())
# at the end of execution file.close() is called automatically.
So as a learning strategy I tried to do the following:
class Derived():
def __enter__(self):
print('__enter__')
def __exit__(self, exc_type, exc_value, traceback):
print('__exit__')
with Derived() as derived:
print(derived)
and I got this output:
__enter__
None
__exit__
My question is then:
- why did
print(derived)
return aNone
object and not aDerived
object?
__enter__
must return the object that is bound todervied
.