如何找到Python中绑定方法的实例?
>>> class A(object):
... def some(self):
... pass
...
>>> a=A()
>>> a.some
<bound method A.some of <__main__.A object at 0x7f0d6fb9c090>>
换句话说,我需要在只得到 "a.some" 的情况下,访问 "a"。
4 个回答
3
试试下面的代码,看看是否对你有帮助:
a.some.im_self
7
>>> class A(object):
... def some(self):
... pass
...
>>> a = A()
>>> a
<__main__.A object at 0x7fa9b965f410>
>>> a.some
<bound method A.some of <__main__.A object at 0x7fa9b965f410>>
>>> dir(a.some)
['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__format__', '__func__', '__get__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'im_class', 'im_func', 'im_self']
>>> a.some.im_self
<__main__.A object at 0x7fa9b965f410>
当然可以!请把你想要翻译的内容发给我,我会帮你把它变得简单易懂。
66
从 Python 2.6 开始,你可以使用一个特殊的属性 __self__
:
>>> a.some.__self__ is a
True
im_self
在 Python 3 里已经不再使用了。
想了解更多细节,可以查看 inspect
模块在 Python 标准库中的说明。