with语句之所以强大背后是由上下文管理支撑的
class My_open(object):
def __init(self,n1,n2):
self.n1 =n1
self.n2=n2
def __enter__(self):
self.heard = open(self.n1,self.n2)
return self.heard
def __exit__(self, exc_type, exc_val, exc_tb):
print("结束")
with My_open('1.txt','r') as file:
file_count = file.read()
print(file_count)
class My_open(object):
def __init__(n1,n2):
self.n1 = n1
self.n2 = n2
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("结束")
def div(self):
return self.n1/self.n2
with My_open(6,2) as mm:
print(mm.div())
上下文管理器搭配的是
__enter()__表示上文,需要操作文件对象
,__exit()__表示下文,with语句会自动完成,即使出现异常
exit中exc_type是发现异常,默认抛出异常信息return False,不抛出用return True