如何在Python中找到绑定方法的实例?

时间:2011-01-13 11:35:23

标签: python class methods

>>> class A(object):  
...         def some(self):  
...                 pass  
...  
>>> a=A()  
>>> a.some  
<bound method A.some of <__main__.A object at 0x7f0d6fb9c090>>

IOW,我只需在移交“a.some”后即可访问“a”。

4 个答案:

答案 0 :(得分:38)

启动python 2.6,您可以使用特殊属性__self__

>>> a.some.__self__ is a
True

im_self在py3k中逐步淘汰。

有关详细信息,请参阅inspect module in the Python Standard Library.

答案 1 :(得分: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>

答案 2 :(得分:3)

尝试以下代码,看看是否有帮助:

a.some.im_self

答案 3 :(得分:3)

我想要这样的东西:

>>> a = A()
>>> m = a.some
>>> another_obj = m.im_self
>>> another_obj
<__main__.A object at 0x0000000002818320>

im_self是类实例对象。