美文网首页
python with

python with

作者: Hmcf | 来源:发表于2019-10-30 17:13 被阅读0次

使用场景:
  网络连接、数据库连接、文件句柄、锁

功能:

它可以自动帮我们释放上下文,就比如文件句柄的操作,如果不使用with语句操作,就需要先open一个文件句柄,结束后要close这个文件句柄,而使用with语句操作的话,退出with代码块的时候就会自动释放掉这个文件句柄

方法:

被跟在with 后面的方法内部必须要实现_enter_和 _exit_方法。
在自定义创建类的时候,在内部实现_enter_方法,with语句一开始就会执行这个方法,再实现_exit_方法,退出with代码块的时候会自动执行这个方法。

举例说明:

class A(object):
    def __init__(self):
        self.f = None

    def __enter__(self):
        print('with语句开始')
        self.f = open('with测试.txt', encoding='utf8', mode='w')
        return self.f
    
    def somfunc():
        # do somethings
        return True  # or not return

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('with语句结束')
        self.f.close()

with A() as f:
    print('start with')
    f.write('hmcf do with')
print('end with')

pythonic用法

with open("test.log","r") as a, open("way.txt","w") as b:
    a.read()
    b.write("hello hmcf")

相关文章

网友评论

      本文标题:python with

      本文链接:https://www.haomeiwen.com/subject/ufqavctx.html