Search code examples
pythonattributeerror

What special method in Python handles AttributeError?


What special method(s?) should I redefine in my class so that it handled AttributeErrors exceptions and returned a special value in those cases?

For example,

>>> class MySpecialObject(AttributeErrorHandlingClass):
      a = 5
      b = 9
      pass
>>>
>>> obj = MySpecialObject()
>>>
>>> obj.nonexistent
'special value'
>>> obj.a
5
>>> obj.b
9

I googled for the answer but couldn't find it.


Solution

  • You would simply define all the other attributes and—if one is missing—Python will fall back on __getattr__.

    Example:

    class C(object):
        def __init__(self):
            self.foo = "hi"
            self.bar = "mom"
    
        def __getattr__(self, attr):
            return "hello world"
    
    c = C()
    print c.foo # hi
    print c.bar # mom 
    print c.baz # hello world
    print c.qux # hello world