在Python中,简洁地使用getattr()并在不为None时使用它。

16 浏览
0 Comments

在Python中,简洁地使用getattr()并在不为None时使用它。

我发现自己经常做以下事情:

attr = getattr(obj, 'attr', None)
if attr is not None:
    attr()
    # 做一些事情,可能是attr()、func(attr)或其他
else:
    # 做其他事情

是否有一种更符合Python风格的写法?这种写法更好吗?(至少在我看来,性能方面并不更好。)

try:
    obj.attr() # 或者其他操作
except AttributeError:
    # 做其他事情

0