上下文管理器在类错误内部实现为“实例没有属性'__exit__'”

时间:2019-02-11 22:59:11

标签: python python-2.7

我正尝试学习python中的上下文管理器,如此处所述:http://book.pythontips.com/en/latest/context_managers.html

从类方法返回实例时,我有一点变化。该对象具有本教程中建议的__enter__和__exit__方法。

class Response():
    def __init__(self, url):
        self.headers = {'Connection': 'dummy'}
        self.body = 'testtest'
        print('SingleRequest()')

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        pass

    def test():
        print('This is test')

class Fetcher():
    def __init__(self):
    print('Fetcher()')

def __enter__(self):
    return self

def __exit__(self, type, value, traceback):
    pass

def get(self, url):
    print ('Fetcher()::get()')
    return Response(url)

def verify():
    with Fetcher() as session:
        with session.get("https://www.google.com/") as response:
            response.test()

if __name__ == "__main__":
    verify()

即使在Response中定义了__exit__,我仍然遇到以下错误。

AttributeError: Response instance has no attribute '__exit__'

0 个答案:

没有答案