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

IOW, I need to get access to "a" after being handed over only "a.some".

Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
mrkafk
  • 617
  • 1
  • 5
  • 4

4 Answers4

65

Starting python 2.6 you can use special attribute __self__:

>>> a.some.__self__ is a
True

im_self is phased out in py3k.

For details, see the inspect module in the Python Standard Library.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
SilentGhost
  • 307,395
  • 66
  • 306
  • 293
  • 1
    Just to make it entirely clear: Use this if you have Python 3. If you're using Python 2, the equivalent is the `im_self` that others have posted. – Thomas K Jan 13 '11 at 11:45
  • 1
    This does not appear to work for dunder methods, e.g. in the original example, `A().__init__.__self__` and `A().__eq__.__self__` do not exist. Any idea if there is an alternative? – Mack Jan 29 '21 at 13:54
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>
MattH
  • 37,273
  • 11
  • 82
  • 84
3

Try following code and see, if it helps you:

a.some.im_self
gruszczy
  • 40,948
  • 31
  • 128
  • 181
3

You want something like this I guess:

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

im_self is the class instance object.

user225312
  • 126,773
  • 69
  • 172
  • 181