How to get instance given a method of the instance?

后端 未结 3 1789
执念已碎
执念已碎 2020-12-06 09:35
class MyClass:
    def myMethod(self):
        pass

myInstance = MyClass()

methodReference = myInstance.myMethod

Now can you get a reference to <

3条回答
  •  孤街浪徒
    2020-12-06 10:06

    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.

提交回复
热议问题