class Data:
def __enter__(self):
print('construct')
class _Data:
def __init__(self) -> None:
self.file = open('foo.txt', 'w')
pass
def cleanup(self) -> None:
print('file closing')
self.file.close()
pass
def work(self) -> None:
print('work')
pass
self.__data_obj = _Data()
return self.__data_obj
def __exit__(self, exc_type, exc_value, traceback) -> None:
print('destruct')
self.__data_obj.cleanup()
pass
if __name__ == "__main__":
with Data() as d:
d.work()
결과:
construct
work
destruct
file closing
enter exit 이라는 메서드도 있구나 - dc App
내기억에 with 구문에 들어갈때/나갈때 호출되는 메소드였던거 같음
raii면 __new__랑 __del__로 해야하는거 아냐?
with를 쓰면 with 구문을 벗어날 때 __exit__ 메서드가 불리는 걸 보장할 수 있음
반면에 __del__ 메서드는 보장할 수 없음
https://stackoverflow.com/questions/1481488/what-is-the-del-method-how-to-call-it