十年老IT知识分享 – 49 – 使用代码描述with语句的作用

1. with语句有什么作用,请用代码解释

  • with语句适用于对资源访问的场合,确保不管使用过程是否发生异常都会执行必要的 “清理”工作
f = open('files/readme.txt', 'r')
data = f.read()
print(data)

'''
1. 没有关闭文件
2. 即使关闭了文件,但在关闭之前如果抛出异常,仍然会无法关闭文件
'''

hello world

I love you

How are you?

f = open('files/readme.txt', 'r')
try:
    data = f.read()
except:
    print('抛出异常')
finally:
    f.close()

with open('files/readme.txt', 'r') as f:
    data = f.read()
    print(data)

hello world

I love you

How are you?

2. 如何将with语句用于一个自定义类

'''
__enter__

__exit__
'''

class MyClass:
    def __enter__(self):
        print('__enter__() is call!')
        return self
    def process1(self):
        print('process1')
        
    def process2(self):
        x = 1/0 
        print('process2')
    def __exit__(self, exc_type, exc_value, traceback):
        print('__exit__() is call!')
        print(f'type:{exc_type}')
        print(f'value:{exc_value}')
        print(f'trace:{traceback}')
        
with MyClass() as my:
    my.process1()
    my.process2()

__enter__() is call!

process1

__exit__() is call!

type:<class 'ZeroDivisionError'>

value:division by zero

trace:<traceback object at 0x0000029AA9F98DC8>

---------------------------------------------------------------------------

ZeroDivisionError                         Traceback (most recent call last)

<ipython-input-10-b97c97f6e5f0> in <module>

     23 with MyClass() as my:

     24     my.process1()

---> 25     my.process2()

<ipython-input-10-b97c97f6e5f0> in process2(self)

     13 

     14     def process2(self):

---> 15         x = 1/0

     16         print('process2')

     17     def __exit__(self, exc_type, exc_value, traceback):

ZeroDivisionError: division by zero

正文完