刚开始时,很抱歉这个问题的标题-我无法提出一个更好的问题。欢迎提出建议。
我为我的课写了__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 - Python-尝试/异常(exception)块的重构-super()方法的双重调用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29545660/