μ΄λ² κ°μλ μμ λ°°μ λ νμ λ¬Έλ²λ€μ΄ λ°νμ΄ λμ΄μ€ κ²μ΄λ€.
μ‘°κΈμ μμνμ§λ§ νλ²μ―€μ λ€μ΄λ΄μΌ ν λ΄μ©μ΄λ λ ν¬κ² λ¨κ³ νλ² λ³΄μ!νΉν μΈλλ°(__ ) λκ°λ‘ μμνλ 맀μ§λ©μλλ κ·Έλμ λ λ§μ£ΌμΉλ©΄ λ°λ‘ μ€νλ μ³€μλλ° μ€λμ λμΈμ μ’ ν΄λ΄μΌκ² λ€~! π
νμΌμ μ€νν λ μ°λ with λ¬Έλ μ¨λ³΄κΈ΄ νμ§λ§ μ΄ν΄λ₯Ό ν΄μ μ°κΈ°λ³΄λ€λ 볡λΆν΄μ μ°κΈ° κΈκΈνλ κ² κ°λ€. μ€λ ν¨ λΆμ~..
__enter__
, __exit__
, with κΈ°λ₯ μ§μ ꡬνcmμ μνλ νμ΄λ°μ μ ννκ² λ¦¬μμ€λ₯Ό ν λΉ, μ 곡, λ°ννλ μν μ ν΄μ€λ€.
κ°μ₯ λνμ μΈ with ꡬ문μ μ΄ν΄ν μ μμ΄μΌνλ€.
file = open('./testfile1.txt','w')
try:
file.write('context manager test1\ncontextllib test1.')
finally:
file.close()
with open('./testfile2.txt','w') as f:
f.write('context manager test2\ncontextllib test2.')
__init__
λ©μλλ ν΄λμ€κ° μ μλ λ μλμΌλ‘ μ€νλλ€.class MyFileWrite():
def __init__(self,file_name, method):
print('myFileWrite started : __init__')
# file.obj = open ν¨μ
self.file_obj = open(file_name,method)
__enter__
λ©μλλ with ꡬ문μ μ§μ
ν λ μλμΌλ‘ νΈμΆλλ€. def __enter__(self):
print('MyFileWrite started : __enter__')
return self.file_obj
__exit__
λ©μλλ with ꡬ문μ λΉ μ Έλκ°κΈ° μ§μ μ μ€νλλ€.exc_type : μμΈ νμ
value: μ€λ₯μ λ΄μ©
trace_back : μ€λ₯λ₯Ό λ°μμν¨ ν¨μ νΈμΆμ μμΆμ ν λ΄μ©
def __exit__(self, exc_type, value, trace_back):
print('MyFileWrite started : __exit__')
if exc_type:
# μμΈ λ°μ μ μ€νλ¨ - customize κ°λ₯ν¨
print('Logging exception {}'.format(exc_type, value, trace_back))
self.file_obj.close()
class MyFileWrite():
def __init__(self,file_name, method):
print('myFileWrite started : __init__')
# file.obj = open ν¨μ
self.file_obj = open(file_name,method)
def __enter__(self):
print('MyFileWrite started : __enter__')
return self.file_obj
def __exit__(self, exc_type, value, trace_back):
print('MyFileWrite started : __exit__')
if exc_type:
print('Logging exception {}'.format(exc_type, value, trace_back))
self.file_obj.close()
with MyFileWrite('./testfile3.txt','w') as f:
f.write('context manager test3\ncontextllib test3.')