當前位置:
首頁 >
python知识点:上下文管理器[__enter__ 和 __exit__ ]
發布時間:2025/4/5
61
豆豆
生活随笔
收集整理的這篇文章主要介紹了
python知识点:上下文管理器[__enter__ 和 __exit__ ]
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
版權聲明:本文為博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/reallocing1/article/details/64526895
上下文管理器(context manager)是Python2.5開始支持的一種語法,用于規定某個對象的使用范圍。一旦進入或者離開該使用范圍,會有特殊操作被調用 (比如為對象分配或者釋放內存)。它的語法形式是with…as…
with語句
with open('some.txt',"w") as f:for i in f:print i自定義上下文管理器
實現函數enter和exit
class Diycontextor:def __init__(self,name,mode):self.name = nameself.mode = modedef __enter__(self):print "Hi enter here!!"self.filehander = open(self.name,self.mode)return self.filehanderdef __exit__(self,*para):print "Hi exit here"self.filehander.close()with Diycontextor('py_ana.py','r') as f:for i in f:print ienter()返回一個對象。上下文管理器會使用這一對象作為as所指的變量?
參考:
- http://kuanghy.github.io/2015/08/08/python-with
- http://www.cnblogs.com/vamei/archive/2012/11/23/2772445.html
總結
以上是生活随笔為你收集整理的python知识点:上下文管理器[__enter__ 和 __exit__ ]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 批处理(.bat)无限循环,定时,固定时
- 下一篇: 使用python xmodem 模块下载