On 13 mai, 01:24, [EMAIL PROTECTED] (Alex Martelli) wrote: > manatlan <[EMAIL PROTECTED]> 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" > > > 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. > > I think what you're asking for is totally weird, and with just about > zero advantages compared with several saner alternatives that have > already been proposed in this thread and that you have rejects, but > sure, it's possible: > > def addaclass(aninst, onemoreclass): > aninst.__class__ = type(aninst.__aclass__.__name__, > (aninst.__aclass__, onemoreclass), {}) > > Alex
I know it's weird ... and solutions given here are a lot saner. But i can't do that at the creation of the instance, because it's not me who has the creation process ... the only things i've got, it's the instance i tried : class MoreMethods: def sayHello(self): print "hello" def addaclass(aninst, onemoreclass): aninst.__class__ = type(aninst.__class__.__name__, (aninst.__class__, onemoreclass), {}) b=gtk.Button("the_label") addaclass(b,MoreMethods) print b.get_label() print b.hello() but got : "TypeError: __class__ assignment: only for heap types" on the last line ... I begin to think that the only solution is to use the module new like Karlo said ... -- http://mail.python.org/mailman/listinfo/python-list