from mirror import LookingGlass manager = LookingGlass() manager monster = manager.__enter__() monster == 'JABBERWOCKY' monster manager manager.__exit__(None, None, None) monster
with open('mirror.py') as fp: src = fp.read(60) len(src) # 60 fp # <_io.TextIOWrapper name='mirror.py' mode='r' encoding='cp949'> fp.closed, fp.encoding # (True, 'cp949') fp.read(60) # 더이상 파일 입출력은 할 수 없다 from mirror import LookingGlass with LookingGlass() as what: print('ABCDEFG') # GFEDCBA; 역순 print(1 / 0) print(what) # YKCOWREBBAJ; 역순 print(what) # JABBERWOCKY; 정상 # with 문 없이도 컨텍스트 매니저를 사용할 수 있다 from mirror import LookingGlass manager = LookingGlass() # <1> manager monster = manager.__enter__() # <2> monster == 'JABBERWOCKY' # <3> eurT ; 여기서 출력함수가 멍키패칭됨 monster #'YKCOWREBBAJ manager.__exit__(None, None, None) # <4> monster # 'JABBERWOCKY'; 출력함수 정상
@author: jiyun """ # 원서 기준 449~453p with open('mirror.py') as fp: src = fp.read(60) print(len(src)) #60 print(fp) # 변수로 살아있음 print(fp.closed, fp.encoding) # 속성 읽기 가능 #print(fp.read(60)) # 파일 닫아서 입출력은 불가능 from mirror import LookingGlass with LookingGlass() as what: print('ABCDEFGHIGKLMNOPQRSTUVWXYZ') # ZYXWVUTSRQPONMLKGIHGFEDCBA print(what) # YKCOWREBBAJ print(what) # enter가 반환한 JABBERWOCKY print('ABCDEFGHIGKLMNOPQRSTUVWXYZ') # ABCDEFGHIGKLMNOPQRSTUVWXYZ """ class LookingGlass: def __enter__(self): import sys self.original_write = sys.stdout.write sys.stdout.write = self.reverse_write return 'JABBERWOCKY' def reverse_write(self, text):
def reverse_write(self, text): self.original_write(text[::-1]) def __exit__(self, exc_type, exc_value, traceback): import sys sys.stdout.write = self.original_write if exc_type is ZeroDivisionError: print('Please DO NOT divide by zero!') return True #Example 15-4: Exercising LookingGlass class w/o a with block from mirror import LookingGlass manager = LookingGlass() manager #<__main__.LookingGlass object at 0x0000021BF1B83588> monster = manager.__enter__() monster == 'JABBERWOCKY' #eurT monster #'YKCOWREBBAJ' manager #>88538B1FB1200000x0 ta tcejbo ssalGgnikooL.__niam__< manager.__exit__(None, None, None) monster #'JABBERWOCKY #Example 15-5:
def __enter__(self): ➊#调用 __enter__ 方法时不传入其他参数 import sys self.original_write = sys.stdout.write ➋ sys.stdout.write = self.reverse_write ➌#替换标准输出为reverse return 'JABBERWOCKY' ➍#print(what)回调用标准输出 def reverse_write(self, text): ➎ self.original_write(text[::-1]) def __exit__(self, exc_type, exc_value, traceback): ➏ import sys ➐ sys.stdout.write = self.original_write ➑#把标准输出改回原来的 if exc_type is ZeroDivisionError: ➒ print('Please DO NOT divide by zero!') return True ➓ >> from mirror import LookingGlass >>> with LookingGlass() as what: ➊ ... print('Alice, Kitty and Snowdrop') ➋ ... print(what) ... pordwonS dna yttiK ,ecilA ➌ YKCOWREBBAJ >>> what ➍ 'JABBERWOCKY' >>> from mirror import LookingGlass >>> manager = LookingGlass() ➊ >>> manager <mirror.LookingGlass object at 0x2a578ac> >>> monster = manager.__enter__() ➋ >>> monster == 'JABBERWOCKY' ➌ eurT
from mirror import LookingGlass import sys with LookingGlass() as enterResult: sys.stdout.write(enterResult) sys.stdout.write("\n") sys.stdout.write("It is reversed") sys.stdout.write("\n") #a = 5 / 0 sys.stdout.write("It is normal\n")
## Test driving the LookingGLass context managers class from mirror import LookingGlass with LookingGlass() as what: print('AKshat', 'ROnaldo', 'Batman') print(what) ## Exercising LookingGlass without a with block from mirror import LookingGlass manager = LookingGlass() manager monster = manager.__enter__() monster == 'JABBEREOCKY'