您的第一个例子很好。甚至官方的Python文档也推荐这种称为EAFP的样式。
就个人而言,我宁愿避免在不必要时嵌套:
def __getattribute__(self, item): try: return object.__getattribute__(item) except AttributeError: pass # fallback to dict try: return self.dict[item] except KeyError: raise AttributeError("The object doesn't have such attribute") from NonePS。
has_key()已在Python 2中弃用了很长时间。请
item in self.dict改用。



