如何用上下文管理器创建类实例?遇AttributeError问题求助
问题原因与解决方法
你的错误根源在于上下文管理器的__enter__方法没有返回实例本身。当使用with ... as var语法时,var接收的是__enter__方法的返回值,而你的__enter__只执行了打印操作,默认返回None,所以后续访问request_session_handler.user时,本质是在访问None的属性,自然抛出AttributeError。
修正后的代码
import requests class RequestSession: # 类名遵循Python大驼峰命名规范 def __init__(self, user="rwelch"): self.user = user self.session = requests.Session() def __enter__(self): print("Creating a new connection...") return self # 关键:返回类实例,让as后的变量能绑定到它 def __exit__(self, exception_type, exception_val, trace): print("Closing connection...") if exception_type: print( "exception type: ", exception_type, "\nexception value: ", exception_val, "\nexception trace: ", trace, ) # 返回True表示已处理异常,不会向外抛出;返回False则会继续传播异常 return True self.session.close() return False
使用示例
with RequestSession() as request_session_handler: print(request_session_handler.user) # 现在可以正常访问属性 # 还可以通过session发送请求 # response = request_session_handler.session.get("https://example.com")
补充说明
- 上下文管理器核心逻辑:
with语句初始化类实例后,会立即调用__enter__方法,将其返回值赋值给as后的变量;代码块执行完毕(或抛出异常)时,自动调用__exit__方法完成资源清理(比如关闭session)。 - 类名遵循大驼峰命名规范,能提升代码可读性与规范性。
内容的提问来源于stack exchange,提问作者tbickford
相关产品推荐
相关产品推荐

