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

时间:2015-04-09 17:56:58

标签: python refactoring try-catch

开始时,抱歉问题的标题 - 我无法想出一个更好的问题。欢迎提出建议。

我为我的班级编写了__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)

它不起作用 - 这似乎很明显。

1 个答案:

答案 0 :(得分:3)

您可以使用循环来避免两次写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行。