给定实例的方法如何获取实例? [英] How to get instance given a method of the instance?

查看:23
本文介绍了给定实例的方法如何获取实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class MyClass:
    def myMethod(self):
        pass

myInstance = MyClass()

methodReference = myInstance.myMethod

如果您现在只能访问 methodReference,那么您现在可以获得对 myInstance 的引用吗?

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

推荐答案

如果您使用的是 Python 3:

If you are using Python 3:

methodReference.__self__

否则:

methodReference.im_self

和类似的标记,对于类:

and by a similar token, for the class:

methodReference.im_class

对于这种代码发现,您应该安装 iPython 并使用 tab,例如,在您的情况下 myReference.+TAB 会给出:

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

因此,您无需担心记住太多东西——您知道该方法可能是由函数对象提供的,并且从 iPython 给出的建议中,通常很明显您正在寻找什么方法/属性.

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.

这篇关于给定实例的方法如何获取实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆