Python: Hack to call a method on an object that isn't of its class

Posted by cool-RR on Stack Overflow See other posts from Stack Overflow or by cool-RR
Published on 2010-05-06T16:00:27Z Indexed on 2010/05/06 16:28 UTC
Read the original article Hit count: 237

Filed under:
|
|
|
|

Assume you define a class, which has a method which does some complicated processing:

class A(object):
    def my_method(self):
        # Some complicated processing is done here
        return self

And now you want to use that method on some object from another class entirely. Like, you want to do A.my_method(7).

This is what you'd get: TypeError: unbound method my_method() must be called with A instance as first argument (got int instance instead).

Now, is there any possibility to hack things so you could call that method on 7? I'd want to avoid moving the function or rewriting it. (Note that the method's logic does depend on self.)

One note: I know that some people will want to say, "You're doing it wrong! You're abusing Python! You shouldn't do it!" So yes, I know, this is a terrible terrible thing I want to do. I'm asking if someone knows how to do it, not how to preach to me that I shouldn't do it.

© Stack Overflow or respective owner

Related posts about python

Related posts about hack