A get() like method for checking for Python attributes

前端 未结 3 1382
执笔经年
执笔经年 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:24

    Do you mean hasattr() perhaps?

    hasattr(object, "attribute name") #Returns True or False
    

    Python.org doc - Built in functions - hasattr()

    You can also do this, which is a bit more cluttered and doesn't work for methods.

    "attribute" in obj.__dict__
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-05 17:38

    For checking if a key is in a dictionary you can use in: 'key' in dictionary.

    For checking for attributes in object use the hasattr() function: hasattr(obj, 'attribute')

    0 讨论(0)
提交回复
热议问题