dynamic bases

Balazs Scheidler bazsi at balabit.hu
Mon Jul 24 06:06:41 EDT 2000


> >So what I basically want is to add a set of methods/attributes to an
> >instance dynamically, so that the methods added can access the
> >attributes of the original instance. My original idea was the following:
> 
> This looks like a job for the 'new' module!
> 
> import new
> 
> class Object:
>     a = 5
> 
>     def __init__(self):
>         self.bonus_method = {}
> 
>     def __getattr__(self, name):
>         if self.bonus_method.has_key(name):
>             return new.instancemethod(self.bonus_method[name], 
>                    self, self.__class__)
>         else:
>             raise AttributeError, name
> 
> def think(self, x):
>     print 'self.a =', self.a, ': x =', x
> 
> a = Object()
> 
> think(a, 1)
> 
> a.bonus_method['think'] = think
> 
> a.think(2)
> 
> 
> 
> ...so why not just say
>   a.think = new.instancemethod(think, a, a.__class__) ?
> ...because this sets up a cicrular reference between
> the object and the new method, and they will never get 
> garbage collected.  If you generate the method in __getattr__,
> the object never holds on to the method reference.

Thanks, you gave me a good idea. I implemented it using new.classobj() and
changed the class object of my instance. This may be ugly as an
implementation, but using it is much easier than having to muck with a hash
to poke function references into.

So for the sake of the archives here's the exact line I used:

self.__class__ = new.classobj(self.__class__.__name__, \
			      self.__class__.__bases__ + (klass,), \
			      self.__dict__)

where klass is a class-object to add to my set of base classes.

-- 
Bazsi
PGP info: KeyID 9AF8D0A9 Fingerprint CD27 CFB0 802C 0944 9CFD 804E C82C 8EB1
     url: http://www.balabit.hu/pgpkey.txt




More information about the Python-list mailing list