I'm trying to create a wrapper class and then overwrite __getattr__
so that requests for attributes that are not in the wrapper class are passed through into the inner object. Below is a toy example where I used a list as the inner object -
class A(object):
def __init__(self):
pass
def __getattr__(self, name):
print 'HERE'
return getattr(self.foo, name)
@property
def foo(self):
try:
return self._foo
except:
self._foo = [2, 1]
return self._foo
I would like to do something like
a = A()
a.sort() # initializes and sorts _foo
print a.foo
which prints [1, 2]
Finally, I need _foo
to initialized when foo
is called for the first time or when someone tries to get an attribute from A()
that is not in A
. Unfortunately, I'm getting in some sort of recursion and HERE
is being printed many times. Is what I want possible?