首页 > 其他 > 详细

上下文管理协议

时间:2020-01-02 16:17:20      阅读:83      评论:0      收藏:0      [点我收藏+]
__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 True
with碰到出错直接结束 运行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

 



上下文管理协议

原文:https://www.cnblogs.com/hb15988111121/p/12133337.html

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