首页 > 其他 > 详细

__enter__和__exit__的用法

时间:2017-04-25 20:39:47      阅读:241      评论:0      收藏:0      [点我收藏+]
#__enter__与__exit__是成对出现的,一般是在进行with obj时才会触发它们

class Open:
def __init__(self,filepath,mode=‘r‘,encode=‘utf-8‘):
self.f=open(filepath,mode=mode,encoding=encode)
# self.filepath =filepath
# self.mode =mode
# self.encoding =encode
def __getattr__(self, item):
return getattr(self.f,item)
def __enter__(self):
return self #如果是self.f,则在f.write(),就不会执行__getattr__方法

def __exit__(self, exc_type, exc_val, exc_tb):
print(‘exit‘)
print(‘exc_type‘,exc_type)
print(‘exc_val‘,exc_val)
print(‘exc_tb‘,exc_tb)
return True

def __del__(self):
print(‘-->‘)
self.f.close()

#f =Open(‘a.txt‘,‘w‘)
with Open(‘a‘,‘w‘) as f:
print(f)
f.write(‘aaaaa\n‘) #f.write(item),因为对象f没有write()方法,就执行__getattr__方法
#即getattr(f.x,write)(item)
f.write(‘bbbb‘)

__enter__和__exit__的用法

原文:http://www.cnblogs.com/IQ-Python/p/6764106.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!