Python from contextlib import closing的使用

1、from contextlib import closing的作用:

管理类上文管理的关闭功能,实例化,运行完成后,会调用类的close方法。

2、用法来源

在学习Kombu队列的操作示例中发现该方法的使用,
https://docs.celeryproject.org/projects/kombu/en/stable/userguide/simple.html#sending-and-receiving-messages

3、简单的示例

from contextlib import closing

class FileHandler(object):
    def __init__(self, rf):
        self.file = rf

    def open(self):
        pass

    def close(self):
        self.file.close()
        print('运行完成closing调用关闭')

if __name__ == '__main__':
    rf = open('tasks.py', 'r', encoding='utf-8')
    with closing(FileHandler(rf)) as file_obj:
        print(file_obj)

运行结果

<__main__.FileHandler object at 0x0000024B859E27C8>
运行完成closing调用关闭
原文地址:https://www.cnblogs.com/ygbh/p/14081707.html