我有一堆类似于此的代码:
                try:
                    auth = page.ItemAttributes.Author
                except:
                        try:
                            auth = page.ItemAttributes.Creator
                        except:
                                auth = None
有没有更好的方法来写出这个逻辑?这使我的代码真的很难阅读.我认为尝试..最终会起作用,但我认为错了
Mar*_*ers 11
您可以使用hasattr来避免try/except块:
auth = None
for attrname in ['Author', 'Creator']:
    if hasattr(page.ItemAttributes, attrname):
        auth = getattr(page.ItemAttributes, attrname)
        break
编写上述内容的另一种方法是使用elsePython for循环的子句:
for attrname in ['Author', 'Creator']:
    if hasattr(page.ItemAttributes, attrname):
        auth = getattr(page.ItemAttributes, attrname)
        break
else:
    auth = None