Injecting methods from one object to another

Rainer Deyke root at rainerdeyke.com
Fri Sep 1 17:44:50 EDT 2000


"Dan Schmidt" <dfan at harmonixmusic.com> wrote in message
news:wku2c00xlb.fsf at turangalila.harmonixmusic.com...
> I want to copy method x from object foo to object bar.
>
>   class Bar:
>       def __init__(self):
>           self.name = 'bar'
>
>       def x (self):
>           print self.name
>
>   class Foo:
>       def __init__(self):
>           self.name = 'foo'
>
>   bar = Bar()
>   foo = Foo()

This is totally impossible in Python without changing Bar, Foo, or the class
of foo.  If this was possible, the following might work:

foo.x = lambda: bar.__class__.x(foo)

However, this won't work because in Python, a method of class X can never be
applied to any object that is not of class X or a subclass of X.

You might try the following: (Warning: possible side effect; uses ugly hack;
resulting object cannot be pickled.)

def assign_method(source_object, target_object, method_name):
  class new_class(target_object.__class__, source_object.__class__):
    pass
  setattr(new_class, method_name, getattr(source_object.__class__),\
    method_name)
  target_object.__class__ = new_class

assign_method(bar, foo, 'x')

Or you might try the following: (Similar warnings apply.)

def call_other_method(object, other_class, name):
  old_class = object.__class__
  object.__class__ = other_class
  try:
    getattr(object, name)()
  finally:
    object.__class__ = old_class

foo.x = lambda: call_other_method(foo, bar.__class__, 'x')



--
Rainer Deyke (root at rainerdeyke.com)
Shareware computer games           -           http://rainerdeyke.com
"In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" - Abigor





More information about the Python-list mailing list