Understanding the difference between __getattr__ and __getattribute__

后端 未结 4 841
深忆病人
深忆病人 2020-11-29 14:44

I am trying to understand the difference between __getattr__ and __getattribute__, however, I am failing at it.

The answer to the Stack Ove

4条回答
  •  执念已碎
    2020-11-29 15:12

    I think the other answers have done a great job of explaining the difference between __getattr__ and __getattribute__, but one thing that might not be clear is why you would want to use __getattribute__. The cool thing about __getattribute__ is that it essentially allows you to overload the dot when accessing a class. This allows you to customize how attributes are accessed at a low level. For instance, suppose I want to define a class where all methods that only take a self argument are treated as properties:

    # prop.py
    import inspect
    
    class PropClass(object):
        def __getattribute__(self, attr):
            val = super(PropClass, self).__getattribute__(attr)
            if callable(val):
                argcount = len(inspect.getargspec(val).args)
                # Account for self
                if argcount == 1:
                    return val()
                else:
                    return val
            else:
                return val
    

    And from the interactive interpreter:

    >>> import prop
    >>> class A(prop.PropClass):
    ...     def f(self):
    ...             return 1
    ... 
    >>> a = A()
    >>> a.f
    1
    

    Of course this is a silly example and you probably wouldn't ever want to do this, but it shows you the power you can get from overriding __getattribute__.

提交回复
热议问题