Skip to content
Advertisement

How to get instance given a method of the instance?

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement