Dynamic subclassing ?

Daniel Nogradi nogradi at gmail.com
Sat May 12 13:07:11 EDT 2007


> > > 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"
> >
> > > so "b" will continue to be a gtk.Button, + methods/attributs of
> > > MoreMethods (it's what i call "dynamic inheritance") ...so, things
> > > like this should work :
> >
> > > - b.set_label("k")
> > > - b.sayHello()
> >
> > > I can't find the trick, but i'm pretty sure it's possible in an easy
> > > way.
> >
> > How about:
> >
> > class MoreMethods:
> >     def  sayHello(self):
> >         print "hello"
> >
> > class myButton( gtk.Button, MoreMethods ):
> >     pass
> >
> > b = myButton( )
> >
> > isinstance( b, gtk.Button )  # True
> > b.sayHello( )  # "hello"
>
> yes, but it needs to recreate an instance (of mybutton) ...
> i can't do that, in my context.
> The only things i've got is my instance "b" (which can be whatever
> object).
> i'd like to add methods/attributes to this instance, by adding a
> heritage of another class.

I think that is not possible, at least in a simple way (there might be
a complicated way of messing with the MRO). Please anyone correct me
if I was wrong.

Daniel



More information about the Python-list mailing list