Question

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.

Was it helpful?

Solution

The example of how to use __getattr__ by Otto Allmendinger overcomplicates its use. 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

OTHER TIPS

Your question isn't clear to me, but it sounds like you are looking for __getattr__ and possibly for __setattr__, and __delattr__.

You have do override __getattr__, it works like this:

class Foo(object):
    def __init__(self):
        self.bar = 'bar'

    def __getattr__(self, attr):
          return 'special value'

foo = Foo()
foo.bar # calls Foo.__getattribute__() (defined by object), returns bar
foo.baz # calls Foo.__getattribute__(), throws AttributeError, 
        # then calls Foo.__getattr__() which returns 'special value'. 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top