views:

481

answers:

3

In the interest of reusing some existing code that was defined as an instance method of a different class, I was tying to do something like the following:

class Foo(object):
  def __init__(self):
    self.name = "Foo"

  def hello(self):
    print "Hello, I am " + self.name + "."

class Bar(object):
  def __init__(self):
    self.name = "Bar"


bar = Bar()
Foo.hello(bar)

but that results in:

TypeError: unbound method hello() must be called with Foo instance as first argument (got Bar instance instead)

Is something like this possible?


I should have been clear that I know this is a bad idea. Obviously the real solution is a bit of refactoring. I just figured there must be a way, and it turns out there is.

Thanks for the comments.

+1  A: 

Looks like this works:

Foo.hello.im_func(bar)

Hello, I am Bar.

I guess I need to read a this little harder...

Jason DeFontes
Yeah, but that's something you should never be doing (except to learn how it works).
David Zaslavsky
Interesting find. But agree that it would be inappropriate to use it for the question asked here.
FogleBird
I don't intend to actually use it. It was just a "how does this work" question. I'll add a note to the original question.
Jason DeFontes
A: 

A while back I wondered about the same "feature" in Perl on PerlMonks, and the general consensus was that while it works (as it does in Python) you should not be doing things that way.

Thilo
+3  A: 

It happens because python wraps class functions as an "unbound method" which performs this type checking. There's some description of the decisions involved in this here.

Note that this type checking has actually been dropped in python 3 (see the note at the end of that article), so your approach will work there.

Brian