I want to make a MixIn class that waits to initialize its super-
classes until an attribute of the object is accessed. Not generally
useful, but desirable in my case. I've written this, and it works, but
would like to take any suggestions you guys have. I've commented out
the "delattr" call because it throws an AttributeError (although I
don't know why).
class LateInitMixIn(o bject):
def __init__(self):
print "LateInit initialization"
self.inited = False
def __getattribute_ _(self, attr):
print "Doing __getattribute_ _"
getattr = lambda attr:object.__g etattribute__(s elf, attr)
if not getattr("inited "):
super(LateInitM ixIn, self).__init__( )
setattr(self, "inited", True)
#delattr(self, "__getattribute __")
return getattr(attr)
class Base(object):
def __init__(self):
print "Base initialization"
self.base = True
class LateInit(LateIn itMixIn, Base): pass
def main():
S = LateInit()
print S
print
print "Should do Base init after now"
print S.base
print S.base
if __name__=="__ma in__": main()
This gives the following output:
LateInit initialization
<__main__.LateI nit object at 0x2a960c1c50>
Should do Base init after now
Doing __getattribute_ _
Base initialization
True
Doing __getattribute_ _
True
classes until an attribute of the object is accessed. Not generally
useful, but desirable in my case. I've written this, and it works, but
would like to take any suggestions you guys have. I've commented out
the "delattr" call because it throws an AttributeError (although I
don't know why).
class LateInitMixIn(o bject):
def __init__(self):
print "LateInit initialization"
self.inited = False
def __getattribute_ _(self, attr):
print "Doing __getattribute_ _"
getattr = lambda attr:object.__g etattribute__(s elf, attr)
if not getattr("inited "):
super(LateInitM ixIn, self).__init__( )
setattr(self, "inited", True)
#delattr(self, "__getattribute __")
return getattr(attr)
class Base(object):
def __init__(self):
print "Base initialization"
self.base = True
class LateInit(LateIn itMixIn, Base): pass
def main():
S = LateInit()
print S
print "Should do Base init after now"
print S.base
print S.base
if __name__=="__ma in__": main()
This gives the following output:
LateInit initialization
<__main__.LateI nit object at 0x2a960c1c50>
Should do Base init after now
Doing __getattribute_ _
Base initialization
True
Doing __getattribute_ _
True
Comment