这是python的良好编码实践吗?

时间:2019-01-06 23:45:09

标签: python if-statement exception-handling code-design

if preset.exists('//*[@id="i0116"]', '10', '1'):
    if (log.enter_username()):
        if preset.exists('//*[@id="i0116"]', '10', '1'):
            if (log.enter_password()):
                locked = unlock(details[0], details[1], browser, ' ', ' ', ' ')
                if not (locked.checkBlocked()):
                    # unlock account
                else:
                    searches = search(details[0], details[1], browser)
            else:
                browser.quit()
                continue
        else:
            browser.quit()
            continue
    else:
        browser.quit()
        continue
else:
    browser.quit()
    continue

我正在用Python开发一个机器人,而且要执行大量异常处理,以至于我可能至少要再获得5个if和else的……

我在这里做错什么了吗?我是否应该在方法本身内部对这些异常进行硬编码,而不是使用控制文件来做到这一点?

2 个答案:

答案 0 :(得分:5)

第一if和第三if not preset.exists('//*[@id="i0116"]', '10', '1'): browser.quit() continue if not log.enter_username(): browser.quit() continue if not log.enter_password(): browser.quit() continue locked = unlock(details[0], details[1], browser, ' ', ' ', ' ') if not (locked.checkBlocked()): # unlock account else: searches = search(details[0], details[1], browser) 检查相同;删除多余的。反转剩余的支票,并尽早退出以消除多余的嵌套。

if not (preset.exists('//*[@id="i0116"]', '10', '1') and
        log.enter_username() and
        log.enter_password()):
    browser.quit()
    continue

locked = unlock(details[0], details[1], browser, ' ', ' ', ' ')
if not locked.checkBlocked():
    # unlock account
else:
    searches = search(details[0], details[1], browser)

然后您可以将三个初始检查合并为一个。

Kernel

答案 1 :(得分:2)

如果您所有的else语句都在做同样的事情,那么您最好也这样写,

if preset.exists('//*[@id="i0116"]', '10', '1') and log.enter_username() and preset.exists('//*[@id="i0116"]', '10', '1') and log.enter_password():
    locked = unlock(details[0], details[1], browser, ' ', ' ', ' ')
    if not (locked.checkBlocked()):
        # unlock account
    else:
        searches = search(details[0], details[1], browser)
else:
    browser.quit()
    continue