How to get instance given a method of the instance?

11,282

Solution 1

If you are using Python 3:

methodReference.__self__

Otherwise:

methodReference.im_self

and by a similar token, for the class:

methodReference.im_class

For this kind of code discovery you should install iPython and use tab, for instance, in your case myReference.+TAB would give:

In [6]: methodReference. methodReference.im_class 
methodReference.im_func   methodReference.im_self

Hence, you don't need to worry about remembering things so much - you know that the method is probably provided by the function object and from the suggestions that iPython gives it's usually obvious what method/attribute you're looking for.

Solution 2

Try this:

methodReference.im_self

If you are using Python 3:

methodReference.__self__

Solution 3

You can work this out yourself - have a look at the dir output:

>>> dir(mr)
['__call__', ... '__str__', '__subclasshook__', 'im_class', 'im_func', 'im_self']

The im_* instances refer to attributes defined for instance methods...

The class it was defined in, the function code block, and the object it is bound to...

Share:
11,282

Related videos on Youtube

Admin
Author by

Admin

Updated on June 03, 2022

Comments

  • Admin
    Admin almost 2 years
    class MyClass:
        def myMethod(self):
            pass
    
    myInstance = MyClass()
    
    methodReference = myInstance.myMethod
    

    Now can you get a reference to myInstance if you now only have access to methodReference?

    • Montre
      Montre over 11 years
      methodReference.im_self (dir() is your friend)
  • Mike Vella
    Mike Vella over 11 years
    The reason I slightly prefer the iPython approach I detail above is that it hides special methods/attributes and formats on the screen slightly cleaner. But of course they're pretty equivalent in terms of functionality and your suggestion doesn't tie the user down to iPython either.
  • Evgeny
    Evgeny over 3 years
    This doesn't work in Python 3. See @dusan answer.
  • Dmytro Bugayev
    Dmytro Bugayev almost 3 years
    old question, but this should now be the accepted answer as it's the only one to provide a solution for python3
  • Mike Vella
    Mike Vella almost 3 years
    @Evgeny thanks - this answer was from 2013, I updated my answer.