What special method in Python handles AttributeError?

What special method (s?) Should I override in my class so that it handles exceptions AttributeErrorand returns a special value in these cases?

For instance,

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

I was looking for an answer, but could not find it.

+3
source share
3 answers

Case Study __getattr__Otto Allmendinger exaggerates its use. You simply define all the other attributes, and if they are missing, Python will return to __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
+4
source

I don’t understand your question, but it looks like you are looking for __getattr__and, possibly, for __setattr__and __delattr__.

+1
source

__getattr__, :

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'. 
+1

Source: https://habr.com/ru/post/1734797/


All Articles