I am trying to create a class to be used with the 'with' statement in python 3 but inside the 'with' statement I don't have access to the object or the methods. For example, Running the following code:
class Openizer:
def __init__(self, something):
self._something = something
def __enter__(self):
print('entered')
def __exit__(self, exc_type, exc_value, traceback):
print('exited')
def print_something(self):
print(self._something)
with Openizer('something') as op:
op.print_something()
raises the following exception:
Traceback (most recent call last):
File "openizer.py", line 16, in <module>
op.print_something()
AttributeError: 'NoneType' object has no attribute 'print_something'
If I try to print(op) it prints 'None'. Why is that? am I using the with statement wrong? what is the correct way? Is it possible to instantiate a class with the 'with' statement and inside the 'with' statement call the instantiated object's methods?
Consider the open() function, it instantiated a file object which can than be read from or written to, I'd like to do something similar.