class ResourceHandler:
def __enter__(self):
print("Resource acquired")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("Resource released")
return True
try:
with ResourceHandler():
print("Processing resource")
raise RuntimeError("Failure")
except RuntimeError:
print("Exception caught")
A
Resource acquired → Processing resource → Resource released → Exception caught
B
Resource acquired → Processing resource → Resource released
C
Resource acquired → Resource released → Processing resource → Exception caught
D
Resource acquired → Processing resource → Exception caught → Resource released
官方解析:
在Python上下文管理器中,`__enter__`方法在进入`with`块时调用,打印'Resource acquired';然后执行`with`块内的代码,打印'Processing resource'并引发`RuntimeError`异常;退出`with`块时调用`__exit__`方法,打印'Resource released',且`__exit__`返回`True`表示异常被抑制,因此异常不会传播到外部`try-except`块,'except RuntimeError'块不会执行,故'Exception caught'未打印。输出顺序为Resource acquired → Processing resource → Resource released。选项A、C、D均错误:A多出'Exception caught';C顺序错误(Resource released在Processing resource前);D顺序错误且多出'Exception caught'。