I am trying to print something when I am accessing to an attribute of a class by using __getattribute__
The big problem here is recursion and the fact I am overriding getattribute method.
I am afraid I have to use metaclass to solve this problem. Anyway if you any answer of this problem.
__getattribute__
is used for all attribute access on your instance. That includes self.recursion
in that method.
You rarely need to use __getattribute__
. If you do actually have a proper use-case for it, avoid attribute access or use super(A, self).__getattribute__()
to avoid infinite recursion problems.
For your usecase (printing something whenever an attribute is being accessed), do use super()
still to return the original attribute:
class A(object):
def meth(self):
return "met"
def __getattribute__(self, name):
print "IN CLASS A"
return super(A, self).__getattribute__(name)
Note that for super()
to work you do need to use a new-style class, inheriting from object
. If you are inheriting from something else, and that something else has a __getattribute__
method, it is already a new-style class.