Python - try/except 块的重构 - 对 super() 方法的双重调用

Python - refactor of try/except block - double call for super() method

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

我为 class 编写了 __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 行。