How do I override __getattr__ in Python without breaking the default behavior?

后端 未结 3 1672
走了就别回头了
走了就别回头了 2020-11-29 15:56

I want to override the __getattr__ method on a class to do something fancy but I don\'t want to break the default behavior.

What\'s the correct way to d

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 16:23

    To extend Michael answer, if you want to maintain the default behavior using __getattr__, you can do it like so:

    class Foo(object):
        def __getattr__(self, name):
            if name == 'something':
                return 42
    
            # Default behaviour
            return self.__getattribute__(name)
    

    Now the exception message is more descriptive:

    >>> foo.something
    42
    >>> foo.error
    Traceback (most recent call last):
      File "", line 1, in 
      File "", line 5, in __getattr__
    AttributeError: 'Foo' object has no attribute 'error'
    

提交回复
热议问题