有没有一种很好的方法来处理Python中的异常?

xpo*_*ter 6 python exception

我有一堆类似于此的代码:

                try:
                    auth = page.ItemAttributes.Author
                except:
                        try:
                            auth = page.ItemAttributes.Creator
                        except:
                                auth = None
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来写出这个逻辑?这使我的代码真的很难阅读.我认为尝试..最终会起作用,但我认为错了

Mar*_*ers 11

您可以使用hasattr来避免try/except块:

auth = None
for attrname in ['Author', 'Creator']:
    if hasattr(page.ItemAttributes, attrname):
        auth = getattr(page.ItemAttributes, attrname)
        break
Run Code Online (Sandbox Code Playgroud)

编写上述内容的另一种方法是使用elsePython for循环的子句:

for attrname in ['Author', 'Creator']:
    if hasattr(page.ItemAttributes, attrname):
        auth = getattr(page.ItemAttributes, attrname)
        break
else:
    auth = None
Run Code Online (Sandbox Code Playgroud)