Dynamic subclassing ?

manatlan manatlan at gmail.com
Sat May 12 10:54:37 EDT 2007


On 12 mai, 17:00, Bruno Desthuilliers
<bdesth.quelquech... at free.quelquepart.fr> wrote:
> manatlan a écrit :
>
> > 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.
>
> You don't even need setattr() here, you can set the attributes directly.
>
>
>
> > 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"
> You don't necessarily need subclassing here. What you want is a typical
> use case of the Decorator pattern:
>
> class MoreMethods(object):
>    def __init__(self, button):
>      self._button = button
>
>    def  sayHello(self):
>      print "hello"
>
>    def __getattr__(self, name):
>      return getattr(self._button, name)
>
>    def __setattr__(self, name, value):
>      if name in dir(self._button):
>        setattr(self._button, name, value)
>      else:
>        object.__setattr__(self, name, value)
>
> b = MoreMethods(gtk.Button())
> b.set_label("k")
> b.say_hello()

except that "b" is not anymore a "gtk.Button", but a "MoreMethods"
instance ...
i'd like that "b" stay a "gtk.Button" ...




More information about the Python-list mailing list