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

后端 未结 3 1671
走了就别回头了
走了就别回头了 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:15

    class A(object):
        def __init__(self):
            self.a = 42
    
        def __getattr__(self, attr):
            if attr in ["b", "c"]:
                return 42
            raise AttributeError("%r object has no attribute %r" %
                                 (self.__class__.__name__, attr))
    

    >>> a = A()
    >>> a.a
    42
    >>> a.b
    42
    >>> a.missing
    Traceback (most recent call last):
      File "", line 1, in 
      File "", line 8, in __getattr__
    AttributeError: 'A' object has no attribute 'missing'
    >>> hasattr(a, "b")
    True
    >>> hasattr(a, "missing")
    False
    

提交回复
热议问题