zoukankan      html  css  js  c++  java
  • Python学习

    python的上下文管理器 with
    with 语句就是为了简化try 和 finally 这种写法

    先看一个try 和 finally的例子
    def try_ex():
        try:
            print("code start")
            raise KeyError
            return 1
        except KeyError as e:
            print("key error")
            return 2
        else:
            print("other error")
            return 3
        finally:
            print("finally")
            return 4
    #上下文管理器协议 __enter__  __exit__ 两个魔法函数
    class Sample:
        def __enter__(self):
            #获取资源
            print("enter")
            return self
    
        def __exit__(self, exc_type, exc_val, exc_tb):
            #释放资源
            print("exit")
    
        def do_thing(self):
            print("doing")
    
    
    with Sample() as sample:
        sample.do_thing()
    #contextlib简化上下文管理器,利用了生成器的特性
    import contextlib
    
    @contextlib.contextmanager #可以将定义的函数变为一个上下文管理器
    def file_open(fiel_name):
        print("file open") #相当于__enter__
        yield {} #将一个函数有生成器特性
        print("file end") #相当于__exit__
    
    with file_open("bobby,txt") as f_opened:
        print("file proccessing")

    #with的使用

    class TianMao(threading.Thread):
        def __init__(self, cond):
            super().__init__(name="天猫精灵")
            self.cond = cond
    
        def run(self):
            with self.cond:
                print("{} : 小爱同学 ".format(self.name))
                self.cond.notify()
                self.cond.wait()
    
    class XiaoAi(threading.Thread):
        def __init__(self, cond):
            super().__init__(name="小爱")
            self.cond = cond
    
        def run(self):
            with self.cond:
                self.cond.wait()
                print("{} : 在 ".format(self.name))
                self.cond.notify()
    
    if __name__ == "__main__":
        from concurrent import futures
        cond = threading.Condition()
        xiaoai = XiaoAi(cond)
        tianmao = TianMao(cond)


  • 相关阅读:
    前端面试集锦
    nodeJs上传附件
    逻辑于 逻辑或
    webpack 学习笔记 (一)
    yum 安装mongodb mysql
    闭包面试提 (2)
    主动的重要性
    1.1一天一题:逆转字符串
    编程提高:一天一道编程题
    iconv将文件编码从gb2312 转换为utf-8
  • 原文地址:https://www.cnblogs.com/mingjie-c/p/10271377.html
Copyright © 2011-2022 走看看