Python

Python基础(35) - With语句的作用

2020-03-08  本文已影响0人  xianling_he

读取文件的几个方法

f = open('C:\\PyTest\\Selenium_OpenSchools\\test_selenium\\综合学习\\files\\temp.txt','r')
print(f.read())
f.close()
f = open('C:\\PyTest\\Selenium_OpenSchools\\test_selenium\\综合学习\\files\\temp.txt','r')
#print(f.read())

try:
    data = f.read()
    print(data)
except:
    print('print error')
finally:
    f.close()
hexianling.png

问题总结:

with的使用

with open('C:\\PyTest\\Selenium_OpenSchools\\test_selenium\\综合学习\\files\\temp.txt','r') as f:
    data = f.read()
    print(data)

将with语句用于自定义的类

class Mycall:
    def __enter__(self):
        print('__enter__() is call')
        return self
    def process1(self):
        print('process1')
    def process2(self):
        print('process2')
    def __exit__(self, exc_type, exc_val, exc_tb):
        print('__exit__() is  call')
        print(f'type:{exc_type}')
        print(f'value: {exc_val}')
        print(f'trace: {exc_tb}')


with Mycall() as my:
    my.process1()
    my.process2()
hexianling.png

总结

  1. with语句可以确保不管是否抛出异常,都会释放资源
    2.如果with语句用于自定义类中,需要实现enter,exit方法,否则会抛出异常

加油 2020-3-8

上一篇 下一篇

猜你喜欢

热点阅读