How to know if an object has an attribute in Python

前端 未结 14 2101
无人及你
无人及你 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:02

    Another possible option, but it depends if what you mean by before:

    undefined = object()
    
    class Widget:
    
        def __init__(self):
            self.bar = 1
    
        def zoom(self):
            print("zoom!")
    
    a = Widget()
    
    bar = getattr(a, "bar", undefined)
    if bar is not undefined:
        print("bar:%s" % (bar))
    
    foo = getattr(a, "foo", undefined)
    if foo is not undefined:
        print("foo:%s" % (foo))
    
    zoom = getattr(a, "zoom", undefined)
    if zoom is not undefined:
        zoom()
    

    output:

    bar:1
    zoom!
    

    This allows you to even check for None-valued attributes.

    But! Be very careful you don't accidentally instantiate and compare undefined multiple places because the is will never work in that case.

    Update:

    because of what I was warning about in the above paragraph, having multiple undefineds that never match, I have recently slightly modified this pattern:

    undefined = NotImplemented

    NotImplemented, not to be confused with NotImplementedError, is a built-in: it semi-matches the intent of a JS undefined and you can reuse its definition everywhere and it will always match. The drawbacks is that it is "truthy" in booleans and it can look weird in logs and stack traces (but you quickly get over it when you know it only appears in this context).

提交回复
热议问题