How to know if an object has an attribute in Python

前端 未结 14 2358
无人及你
无人及你 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 12:56

    I think what you are looking for is hasattr. However, I'd recommend something like this if you want to detect python properties-

    try:
        getattr(someObject, 'someProperty')         
    except AttributeError:
        print "Doesn't exist"
    else
        print "Exists"
    

    The disadvantage here is that attribute errors in the properties __get__ code are also caught.

    Otherwise, do-

    if hasattr(someObject, 'someProp'):
        #Access someProp/ set someProp
        pass
    

    Docs:http://docs.python.org/library/functions.html
    Warning:
    The reason for my recommendation is that hasattr doesn't detect properties.
    Link:http://mail.python.org/pipermail/python-dev/2005-December/058498.html

提交回复
热议问题