A get() like method for checking for Python attributes

前端 未结 3 1391
执笔经年
执笔经年 2020-12-05 17:05

If I had a dictionary dict and I wanted to check for dict[\'key\'] I could either do so in a try block (bleh!) or use the get()<

3条回答
  •  感情败类
    2020-12-05 17:35

    A more direct analogue to dict.get(key, default) than hasattr is getattr.

    val = getattr(obj, 'attr_to_check', default_value)
    

    (Where default_value is optional, raising an exception on no attribute if not found.)

    For your example, you would pass False.

提交回复
热议问题