gpt4 book ai didi

Python - 重构 try/except block - 双重调用 super() 方法

转载 作者:行者123 更新时间:2023-11-30 23:13:02 25 4
gpt4 key购买 nike

一开始,对问题的标题感到抱歉 - 我想不出更好的标题。欢迎提出建议。

我为我的类编写了 __init__ 方法,该方法效果很好,但看起来很丑。可以改进吗?我的意思是调用函数 super() 的重复行。

def __init__(self, *args, **kwargs):
"""
Creates selenium driver.

:param args: Non-keyword variables passed to selenium driver.
:param kwargs: Keyword variables passed to selenium driver.
"""

try:
phantomjs_path = 'node_modules/.bin/phantomjs'
super().__init__(phantomjs_path, *args, **kwargs)
except WebDriverException:
phantomjs_path = 'phantomjs'
super().__init__(phantomjs_path, *args, **kwargs)
<小时/>

更新:

try:
phantomjs_path = 'node_modules/.bin/phantomjs'
except WebDriverException:
phantomjs_path = 'phantomjs'
finally:
super().__init__(phantomjs_path, *args, **kwargs)

它不起作用 - 这似乎是显而易见的。

最佳答案

您可以使用循环来避免将 super 行写入两次:

for phantomjs_path in ('node_modules/.bin/phantomjs', 'phantomjs'):
try:
super().__init__(phantomjs_path, *args, **kwargs)
break
except WebDriverException:
pass

否则,您在这里无能为力。 Python 中处理异常的唯一方法是使用 try/except 构造,该构造始终至少需要 4 行。

关于Python - 重构 try/except block - 双重调用 super() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29545660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com