首页 新闻 会员 周边 捐助

以下Python代码执行后,控制台的输出结果是?

0
[已关闭问题] 关闭于 2025-11-24 13:07

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
 
正确答案:B
官方解析:
在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'。
*Tesla*的主页 *Tesla* | 小虾三级 | 园豆:1152
提问于:2025-11-24 13:07
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册