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

2024-05-23 13:43:41 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我有一个小小的变化,我从类方法返回一个实例。该对象具有教程中建议的uuu enter_uuu和uuu exit_uuu方法

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()

即使响应中定义了_uexit _uu,我也会得到以下错误

AttributeError: Response instance has no attribute '__exit__'

Tags: 方法testselfcomurlgetreturnresponse