How to know if an object has an attribute in Python

前端 未结 14 2070
无人及你
无人及你 2020-11-22 12:19

Is there a way in Python to determine if an object has some attribute? For example:

>>> a = SomeClass()
>>> a.someProperty = value
>>         


        
14条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 13:01

    EDIT:This approach has serious limitation. It should work if the object is an iterable one. Please check the comments below.

    If you are using Python 3.6 or higher like me there is a convenient alternative to check whether an object has a particular attribute:

    if 'attr1' in obj1:
        print("attr1 = {}".format(obj1["attr1"]))
    

    However, I'm not sure which is the best approach right now. using hasattr(), using getattr() or using in. Comments are welcome.

提交回复
热议问题