hasattr() vs try-except block to deal with non-existent attributes

前端 未结 12 2323
庸人自扰
庸人自扰 2020-11-30 23:29
if hasattr(obj, \'attribute\'):
    # do somthing

vs

try:
    # access obj.attribute
except AttributeError, e:
    # deal with Attr         


        
12条回答
  •  时光取名叫无心
    2020-11-30 23:58

    If it's just one attribute you're testing, I'd say use hasattr. However, if you're doing several accesses to attributes which may or may not exist then using a try block may save you some typing.

提交回复
热议问题