上下文管理协议

故事扮演 提交于 2020-01-02 15:52:10
__enter__    (输入)  和__exit__    (出口)
class Open:
    def __init__(self,name):
        self.name = name

    def __enter__(self):
        print('执行enter')
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('执行exit')


with Open('a.txt') as f:
    print(f)
    print(f.name)
    print('----------->')
    print('----------->')
print('000000000000')

执行enter                #__enter__  运行
<__main__.Open object at 0x02F3E118>
a.txt
----------->
----------->
执行exit                 #__exit__   运行
000000000000            #with运行完毕    运行其他语句

__exit__(self, exc_type, exc_val, exc_tb)
exc_type, exc_val, exc_tb分别代表什么?
class Open:
    def __init__(self,name):
        self.name = name

    def __enter__(self):
        print('执行enter')
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('执行exit')
        print(exc_type)
        print(exc_val)
        print(exc_tb)


with Open('a.txt') as f:
    print(f)
    print(f.sdadsadsa)
    print(f.name)
    print('----------->')
    print('----------->')
    print('----------->')
    print('----------->')
    print('----------->')
print('000000000000')

执行enter                                          #执行__enter__
Traceback (most recent call last):
<__main__.Open object at 0x0365E118>              #执行print(f)
File "D:/pycharm/python_s3/2020-1-2/上下文管理协议.py", line 18, in <module>
执行exit                         #出错执行__exit__
print(f.sdadsadsa)                   
<class 'AttributeError'>               #执行print(exc_type)
AttributeError: 'Open' object has no attribute 'sdadsadsa'
'Open' object has no attribute 'sdadsadsa'        #执行print(exc_val)
<traceback object at 0x036DD088>           #执行print(exc_tb)

 

 

__exit__   添加 return Truewith碰到出错直接结束    运行with之后的语句
class Open:
    def __init__(self,name):
        self.name = name

    def __enter__(self):
        print('执行enter')
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('执行exit')
        print(exc_type)
        print(exc_val)
        print(exc_tb)
        return True


with Open('a.txt') as f:
    print(f)
    print(f.sdadsadsa)
    print(f.name)
    print('----------->')
    print('----------->')
    print('----------->')
    print('----------->')
    print('----------->')
print('000000000000')

执行enter
<__main__.Open object at 0x0300E118>
执行exit
<class 'AttributeError'>
'Open' object has no attribute 'sdadsadsa'
<traceback object at 0x0308C088>
000000000000

 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!