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.
Looks like this works:
I guess I need to read a this little harder...
This is an old question, but Python has evolved and looks like it's worth pointing it out:
with Python 3 there's no more
<unbound method C.x>
, since an unbound method is simply a<function __main__.C.x>
!Which probably means the code in the original question should not be considered /that/ off. Python has always been about duck typing in any case, hasn't it?!
Refs:
Alternative solution in Py2
Note that there's also an alternative solution to the "explorative" question (see Python: Bind an Unbound Method?):
Ref:
Some ipython code samples
python 2
python 3
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.
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.