Dynamic subclassing ?

manatlan manatlan at gmail.com
Sun May 13 04:13:22 EDT 2007


On 12 mai, 20:47, Steven Bethard <steven.beth... at gmail.com> wrote:
> 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

Yes ! it seems very good ...
I will try that too
thanks a lot ...

class MoreMethods:
    val=12
    def hello(self):
        self.val=13
        return self.get_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)))
       else:
           setattr(obj, name, value)

b=gtk.Button("the_label")
add_methods(b,MoreMethods)
print b.get_label()
print b.val
print b.hello()
print b.val




More information about the Python-list mailing list