Six, Python IO and anomalies 4, with statement

4, with the statement

Description : with statements Management Resources Close

with open('data.txt', 'r', True, 'GBK') as f:    # 把打开文件放在 with 语句中,可自动关闭文件
    print(f.read())
第一行
第二行
第三行

Principle :

  • With statement management of resources must be a realization context management protocol (context manage protocol) class.

  • Implement context management protocol must implement two methods:

    • context_manager._ Enter _ (): automatically enters the context manager invokes this method.

      • This method will be executed before the block of code with;
      • If the with statement has as clause, then the return value of this method will be assigned to a variable as the clause;
      • The method may return multiple values, so as clause can specify the plurality of variables (variables must be made by a plurality of "()" tuple consisting enclosed).
    • context_manger._ Exit _ (exc_type, exc_value, exc_traceback): Exit context manager automatically caller of the method.

      • This method is performed after code block with execution;

      • If the code block with the successful execution ends automatically call the method, this method calls the three parameters are None;

      • If the block of code with as exception, the program automatically invoke this method, the abnormality information sys.exc_info obtained as calling the method (using Help (sys.exc_info) see the function described).

        • ex_type: Exception Type
        • All parameter values ​​passed outliers, create an exception: ex_value
        • ex_traceback: abnormal traceback objects, the number of rows containing the error, the location data.
        import traceback
        import sys
        try:
             raise ValueError(10, '抛出异常')    # 10 为自定义的异常编号
        except Exception as ex:
            ex_type, ex_value, ex_traceback = sys.exc_info()
            print(ex_type)
            print(ex_value)
            for stack in traceback.extract_tb(ex_traceback):
                print(stack)
        
        <class 'ValueError'>
        (10, '抛出异常')
        <FrameSummary file test.py, line 4 in <module>>
        

Analysis :

  • A class implements __enter __ () and __exit __ (exc_type, exc_value, exc_traceback) method, the program can use with statements to manage it;
  • The __exit parameter __ () method to determine whether an exception is encountered during execution code block with
class FkResource:
    def __init__(self, tag):
        self.tag = tag
        print('---构造方法---')
        
    # 进入with 语句时会执行该方法
    def __enter__(self):
        print('该资源的tag:', self.tag)
        return 'python'       # 此处的返回值就是 as 语句中变量的值
 
    def __exit__(self, ex_type, ex_value, ex_traceback):
        if ex_traceback:      # ex_traceback 若存在,说明因为异常退出
            print('出现异常(关闭资源)')
        else:
            print('正常结束(关闭资源)')
with FkResource('java') as fk:
    print('fk为:', fk)
    print('before')
    print('活动')
    print('after')
---构造方法---
该资源的tag: java
fk为: python
before
活动
after
正常结束(关闭资源)
with FkResource('java') as fk:
    print('fk为:', fk)
    print('before')
    raise Exception(10, '自定义异常')
    print('after')
---构造方法---
该资源的tag: java
fk为: python
before
出现异常(关闭资源)
--------------------------------------
...(省略)
Exception: (10, '自定义异常')

Analysis : steps.

  1. Expression (FkResource ( 'java')) after the execution with clause
  2. __Enter__ execution method and change the return value as a variable is assigned to clause
  3. Complete or encounter with a block of statements executed automatically __exit__ method exception

Guess you like

Origin blog.csdn.net/qq_36512295/article/details/94740044