A get() like method for checking for Python attributes

前端 未结 3 1384
执笔经年
执笔经年 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__
    

提交回复
热议问题