【python】with语句和上下文管理器

àì夳堔傛蜴生んèń 2022-11-29 11:45 239阅读 0赞

1.with语句

我们经常看到with open(xxxx,xxxx) as f这样的语句打开文件,但是却不用关闭,实际上它会自动调用了上下文管理器的上下文方法。当使用with语句时会调用上文方法__enter__(),with语句结束时会自动调用下文方法 __exit__() 进行关闭
使用语法:with 上下文管理器对象 as 上文函数执行的返回资源:

2.演示(打开文件)

我们一般用open()函数打开一个文件,现在我们定义一个类来演示上下文被调用

  1. class File(object):
  2. def __init__(self, file_name, mode):
  3. self.file_name = file_name
  4. self.mode = mode
  5. # 调用上文
  6. def __enter__(self):
  7. print('执行上文')
  8. self.file = open(self.file_name, self.mode)
  9. return self.file # 返回的内容,即with语句后的as指向的内容
  10. # 调用下文
  11. def __exit__(self, exc_type, exc_val, exc_tb):
  12. print('执行下文')
  13. self.file.close()
  14. if __name__ == '__main__':
  15. with File('test.txt', 'r') as file:
  16. data = file.read()
  17. print(data)
  18. ***
  19. 结果:
  20. 执行上文
  21. good morning(读取到的test.txt的内容)
  22. 执行下文
  23. ***

3.演示(数据库)

  1. import pymysql
  2. class SQL(object):
  3. def __init__(self, host, user, password, database):
  4. self.host = host
  5. self.user = user
  6. self.password = password
  7. self.database = database
  8. def __enter__(self):
  9. print('执行上文')
  10. self.__conn = pymysql.connect(host=self.host, port=3306, user=self.user, password=self.password,
  11. database=self.database, charset='utf8')
  12. self.__cs = self.__conn.cursor()
  13. return self.__cs
  14. def __exit__(self, exc_type, exc_val, exc_tb):
  15. print('执行下文')
  16. if exc_type:
  17. self.__conn.rollback()
  18. print(exc_val)
  19. else:
  20. self.__conn.commit()
  21. self.__cs.close()
  22. self.__conn.close()
  23. return True
  24. if __name__ == '__main__':
  25. with SQL('localhost', 'root', 'mysql', 'jing_dong') as cs:
  26. row_num = cs.execute('select * from goods')
  27. if row_num > 0:
  28. for i in cs.fetchall():
  29. print(i)

发表评论

表情:
评论列表 (有 0 条评论,239人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Python上下文管理

    1. 上下文管理器 一个类只要实现了 `__enter__()` 和 `__exit__()` 这个两个方法,通过该类创建的对象我们就称之为上下文管理器。 上下文管理器