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

Python-try/except块的重构-super()方法的双重调用,python,refactoring,try-catch,Python,Refactoring,Try Catch,在Begging,我为问题的标题感到抱歉——我想不出更好的题目了。欢迎提出建议 我为我的类编写了\uuuuu init\uuuu方法,它工作得很好,但看起来很难看。可以改进吗?我指的是重复的线路调用函数super() 更新: try: phantomjs_path = 'node_modules/.bin/phantomjs' except WebDriverException: phantomjs_path = 'phantomjs' finally: super()

在Begging,我为问题的标题感到抱歉——我想不出更好的题目了。欢迎提出建议

我为我的类编写了
\uuuuu init\uuuu
方法,它工作得很好,但看起来很难看。可以改进吗?我指的是重复的线路调用函数
super()


更新:

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行代码。

您真的需要phantomjs_path变量吗?@GergelySipkai:不,我不需要它。我只想成功地调用
super()
,然后你应该只调用super()。@GergelySipkai:Double
super()
,不定义变量当然有效。但它们仍然是重复的行。:)正如你所说,可能没有其他办法。我认为您的解决方案会更好(尽管代码更长)。
for phantomjs_path in ('node_modules/.bin/phantomjs', 'phantomjs'):
    try:
        super().__init__(phantomjs_path, *args, **kwargs)
        break
    except WebDriverException:
        pass