在python中处理不存在的属性的最优雅方法是什么?

时间:2017-03-14 19:42:00

标签: python duck-typing

我很擅长打字并提出以下问题。

有没有更好的方法

try:
    what_i_want = obj.some_attr
except AttributeError: # this attribute does not exist, or something other wrong happened
    what_i_want = default_value_for_what_i_want

我希望在一个简单的语句中看到类似于典型获取值或None的内容,例如

if(i is not None and i < 10):

1 个答案:

答案 0 :(得分:2)

您可以使用内置的getattr

what_i_want = getattr(obj, 'some_attr', default_value)