How to handle an error within any Python class?

Asked

Viewed 42 times

3

If I do something like:

class Foo(object):
    pass

print(Foo().python)

**OUTPUT:**
AttributeError: 'Foo' object has no attribute 'python'

How can I treat this exception within my class, rather than outside it, for example:

class Foo(object):
    def any_except_method():
        return 'default_value'

print(Foo().python)

**OUTPUT:**
'default_value'

1 answer

3


If you want to deal with one AttributeError raised by whichever access to an attribute not in its class, implement the special method __getattr__:

class Foo(object):
    def __getattr__(self, attr):
        return 'default_value'

Foo().python  # output: 'default_value'

More information on official documentation.

  • It worked, thank you very much @jfaccioni!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.