I am trying to understand the difference between __getattr__
and __getattribute__
, however, I am failing at it.
The answer to the Stack Ove
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__
.