How to get instance given a method of the instance?

心已入冬 提交于 2019-12-17 19:57:36

问题


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?


回答1:


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.




回答2:


Try this:

methodReference.im_self

If you are using Python 3:

methodReference.__self__



回答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...



来源:https://stackoverflow.com/questions/14588905/how-to-get-instance-given-a-method-of-the-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!