I've made myself a lazy variable class, and used it in another class. How can I then access the attributes of the lazy variable class? I have tried __getattr__ without luck. Here's an example:
class lazyobject(object):
def __init__(self,varname,something='This is the something I want to access'):
self.varname = varname
self.something = something
def __get__(self, obj, type=None):
if obj.__dict__.has_key(self.varname):
print "Already computed %s" % self.varname
return obj.__dict__[self.varname]
else:
print "computing %s" % self.varname
obj.__dict__[self.varname] = "something else"
return obj.__dict__[self.varname]
class lazyobject2(lazyobject):
def __getattr__(self):
return self.something
class dummy(object):
def __init__(self):
setattr(self.__class__, 'lazy', lazyobject('lazy'))
class dummy2(object):
def __init__(self):
setattr(self.__class__, 'lazy', lazyobject2('lazy'))
d1 = dummy()
d2 = dummy2()
try:
print "d1.lazy.something - no getattr: ",d1.lazy.something
except:
print "d2.lazy is already computed - can't get its .something because it's now a string!"
print "d1.lazy - no getattr: ",d1.lazy
try:
print "d2.lazy.something - has getattr: ",d2.lazy.something
except:
print "d2.lazy is already computed - can't get its .something because it's now a string!"
print "d2.lazy - no getattr: ",d2.lazy
This prints:
d1.lazy.something - no getattr: computing lazy
d2.lazy is already computed - can't get its .something because it's now a string!
d1.lazy - no getattr: something else
d2.lazy.something - has getattr: computing lazy
d2.lazy is already computed - can't get its .something because it's now a string!
d2.lazy - no getattr: something else
What I would like it to print:
d1.lazy.something - no getattr: This is the something I want to access
computing lazy
d1.lazy - no getattr: something else
The above example is contrived but I hope gets the point across. Another way to phrase my question is: How can I bypass the __get__ method when accessing a class attribute?