Dynamic subclassing ?

Steven Bethard steven.bethard at gmail.com
Sat May 12 14:47:08 EDT 2007


manatlan wrote:
> I've got an instance of a class, ex :
> 
> b=gtk.Button()
> 
> I'd like to add methods and attributes to my instance "b".
> I know it's possible by hacking "b" with setattr() methods. But i'd
> like to do it with inheritance, a kind of "dynamic subclassing",
> without subclassing the class, only this instance "b" !
> 
> In fact, i've got my instance "b", and another class "MoreMethods"
> 
> class MoreMethods:
>     def  sayHello(self):
>           print "hello"
> 
> How could i write ...
> 
> "b = b + MoreMethods"

You can simply bind the methods you want to add to the Button instance. 
That means doing the equivalent of ``b.sayHello = sayHello.__get__(b)``. 
For example::

     >>> class Button(object):
     ...     def set_label(self, label):
     ...         print 'setting label:', label
     ...
     >>> def add_methods(obj, cls):
     ...     for name, value in cls.__dict__.items():
     ...         if callable(value) and hasattr(value, '__get__'):
     ...             setattr(obj, name, value.__get__(obj, type(obj)))
     ...
     >>> b = Button()
     >>> b.set_label('k')
     setting label: k
     >>> b.say_hello()
     Traceback (most recent call last):
       File "<interactive input>", line 1, in <module>
     AttributeError: 'Button' object has no attribute 'say_hello'
     >>> class MoreMethods(object):
     ...     def say_hello(self):
     ...         print 'hello'
     ...
     >>> add_methods(b, MoreMethods)
     >>> b.set_label('m')
     setting label: m
     >>> b.say_hello()
     hello

HTH,

STeVe



More information about the Python-list mailing list