• python之with的使用


      python之with使用                                      

      with工作原理           

    紧跟with后面的语句被求值后,返回对象的__enter__()方法被调用,这个方法的返回值将被赋值给as后面的变量。当with后面的代码块全部被执行完之后,将调用前面返回对象的__exit__()方法

      代码演示                  

     1 class TestWith(object):
     2 
     3     def __init__(self):
     4         super().__init__()
     5 
     6     # __enter__()方法会在with后面的语句被求值后执行,并将这个方法的返回值返回给with语句后面as跟着的参数
     7     def __enter__(self):
     8         print("I'm enter function")
     9         return "Foo"
    10 
    11     # __exit__()方法会在with语句后面的语句块执行完后执行
    12     def __exit__(self, types, value, true):
    13         print("I'm exit function")
    14 
    15     def test(self):
    16         print("I'm test")
    17 
    18 
    19 with TestWith() as t:
    20     print(t)

     运行结果:

    在with调用TestWith类后会先执行TestWith类的__enter()__方法,并将这个方法的返回值赋值给as后面的t,在执行完with下面的代码块后会执行TestWith类的__exit__()方法

    1 I'm enter function
    2 Foo
    3 I'm exit function
  • 相关阅读:
    RTP 协议
    RTSP 协议分析 (一)
    RTSP协议分析(二)
    CreateRemoteThread简单应用
    函数开始处的MOV EDI, EDI的作用
    eax,ebx,ecx,edx,esi,edi,ebp,esp寄存器的作用
    C++函数调用原理理解
    WinDBG常用断点命令
    利用bu命令下延迟断点
    Windbg 查看SSDT表
  • 原文地址:https://www.cnblogs.com/Myarticles/p/8908594.html
Copyright © 2020-2023  润新知