具体实现思路依赖在类中的两个魔法方法:__enter__、__exit__
本博客来源于 https://stackoverflow.com/questions/1984325/explaining-pythons-enter-and-exit
比如存在需求:在 with 管理器中创建 database 的链接,跳出 with 管理器之后关闭掉链接
代码示例
class DatabaseConnection(object):
def __enter__(self):
# make a database connection and return it
...
return self.dbconn
def __exit__(self, exc_type, exc_val, exc_tb):
# make sure the dbconnection gets closed
self.dbconn.close()
...
# with 管理器的使用
with DatabaseConnection() as mydbconn:
# do stuff