Wrapping classes

Paolino paolo_veronelli at tiscali.it
Fri Sep 23 06:06:17 EDT 2005


Paolino wrote:

> class NotInitializedObjects(type):
>   def __init__(cls,*_):
>     realInit=cls.__init__
>     def __newInit__(self,*pos,**key):
>       def _init():
>         realInit(self,*pos,**key)
>       self._init=_init
>     cls.__init__=__newInit__
>     def __getattribute__(self,attr):
>       def getter(attr):
>         return object.__getattribute__(self,attr)
>       if '_init' in getter('__dict__'):
>         getter('_init')()
>         del self._init
>       return getter(attr)
>     cls.__getattribute__=__getattribute__
> 

A lighter solution can be overriding __getattr__.
This will produce more object-like behaving instances even when not 
initialized, aka you can call methods and access class attributes 
without triggering the init (not very useful)

class NotInitializedObjects(type):
   def __init__(cls,*_):
     realInit=cls.__init__
     def __newInit__(self,*pos,**key):
       def _init():
         realInit(self,*pos,**key)
       self._init=_init
     cls.__init__=__newInit__
     def __getattr__(self,attr):
       if hasattr(self,'_init'):
         self._init()
         del self._init
         if hasattr(self,attr):
           return getattr(self,attr)
       raise AttributeError
     cls.__getattr__=__getattr__

### Test with previous testing code

A cleaner solution is decoupling the intensive calculation attributes 
from __init__ and use descriptors for them.But this is impossible if 
/the/ instance value is the intensive one to be calculated.

Ciao Paolino


		
___________________________________ 
Aggiungi la toolbar di Yahoo! Search sul tuo Browser, e'gratis! 
http://it.toolbar.yahoo.com



More information about the Python-list mailing list