with open(path) as f:
s = f.read()
みたいな感じでみるwith
ですが、
他の言語にはないので、なんとなくスルーして使っていましたが
すごく便利で簡単に使えるので、おすすめです。
毎回同じ初期化、終了処理を行うものを綺麗に共通化することができます。
class Hoge():
def __init__(self, arg):
'''引数がある場合はinitを利用する'''
print(arg)
print('init ←entryより先')
def __enter__(self):
'''開始処理'''
print('entry')
# withのasになる部分がここ
return self
def __exit__(self, exc_type, exc_val, exc_tb):
'''終了処理'''
print('exit')
if exc_type is not None:
# エクセプションが起きた場合は、情報が入る
print(exc_type)
print(exc_val)
print(exc_tb)
# Trueを返すとエクセプションをraiseしない
return True
def test():
print('おはよう僕の世界')
クラスに__entry__
と__exit__
を実装すれば、withで使えるようになります!
with Hoge('hello') as hoge:
hoge.test()
hello
init ←entryより先
entry
おはよう僕の世界
exit