dynamic bases

Jake Speed speed at ?.com
Fri Jul 21 12:02:01 EDT 2000


bazsi at balabit.hu (Balazs Scheidler) wrote in
<20000721171635.B1431 at balabit.hu>: 


>
>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.

-Speed!



More information about the Python-list mailing list