2

Is it possible to access the object to which a bound method is bound?

class NorwegianBlue(object):

    def hello(self):
        print "Well, he's...he's, ah...probably pining for the fjords"

    def some_method(self):
        pass

thing = NorwegianBlue().some_method
the_instance = ???
thing.im_class.hello(the_instance)
wim
  • 338,267
  • 99
  • 616
  • 750

1 Answers1

4

Bound methods have a __self__ and im_self attribute:

>>> thing = NorwegianBlue().some_method
>>> thing.__self__
<__main__.NorwegianBlue object at 0x100294c50>
>>> thing.im_self
<__main__.NorwegianBlue object at 0x100294c50>

im_self is the old name; __self__ is the Python 3 name.

You may find the inspect module documentation helpful; it contains a table of attributes per object type.

The attributes are described in more detail in the reference Data Model documentation.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343