python上下文管理器[__enter__ 和 __exit__ ] (with调用时才会使用,普通调用不会使用)

with语句

with open('some.txt',"w") as f:
    for i in f:
        print i

自定义上下文管理器

实现函数enterexit

class Diycontextor:
    def __init__(self,name,mode):
        self.name = name
        self.mode = mode

    def __enter__(self):
        print "Hi enter here!!"
        self.filehander = open(self.name,self.mode)
        return self.filehander

    def __exit__(self,*para):
        print "Hi exit here"
        self.filehander.close()


with Diycontextor('py_ana.py','r') as f:
    for i in f:
        print i
  •  

enter()返回一个对象。上下文管理器会使用这一对象作为as所指的变量 
参考:

出处:https://blog.csdn.net/reallocing1/article/details/64526895

阅读更多

没有更多推荐了,返回首页