Injecting methods from one object to another

Dan Schmidt dfan at
Fri Sep 1 20:35:28 CEST 2000

I want to copy method x from object foo to object bar.

  class Bar:
      def __init__(self):
 = 'bar'

      def x (self):

  class Foo:
      def __init__(self):
 = 'foo'

  bar = Bar()
  foo = Foo()


  foo.x = bar.x

doesn't work, because foo.x is still bound to bar:


I want it to be bound to foo.

  foo.x = bar.x
  foo.x.im_self = foo

doesn't work, because im_self is read-only.

I tried to get the actual function Bar.x and bind it to foo by hand:

  foo.x = bar.x.im_class.x.im_func
but that didn't work either:

  TypeError: not enough arguments; expected 1, got 0

though it's close:


The only problem is that foo.x is returning a function, not a method
bound to foo.  I thought that if x was a function member of foo, then
foo.x would automatically bind it, but it's not.

I'm sure that I'm almost there and that there's a very simple
solution, but I can't find it.  Anyone have the answer?

Thanks in advance.

                 Dan Schmidt |
Honest Bob CD now available! |

More information about the Python-list mailing list