4

In pyton code I've got a bound method of some object. Knowing only this bound method I would like to know what is the class of that object. Is it possible?

Here is sample code:

>>> class x:
...     def method(self):
...             pass
...
>>> x
<class __main__.x at 0xb737d1ac> 
>>> x_instance = x()
>>> x_instance
<__main__.x instance at 0xb737c7cc>
>>> boundmethod = x_instance.method
>>> boundmethod
<bound method x.method of <__main__.x instance at 0xb737c7cc>>
>>> str(boundmethod)
'<bound method x.method of <__main__.x instance at 0xb737c7cc>>'

Let's assume I know only boundmethod. How to determine that the class is x?

running.t
  • 5,329
  • 3
  • 32
  • 50
  • After taking a look at [this](http://stackoverflow.com/questions/4679592/how-to-find-instance-of-a-bound-method-in-python) question I know i could do sth like `boundmethod.im_self.__class__.__name__`. Is there any easier way? – running.t Apr 10 '13 at 11:40
  • Why would there be an easier way? Why are you passing around bound methods instead of the objects they are bound to? – Wooble Apr 10 '13 at 11:43
  • And looking at jamylak comment I finally found the solution: `boundmethod.im_class.__name__`. Thanks. – running.t Apr 10 '13 at 11:43
  • @running.t try a `dir(...)` next time, since you were so close you would have found it had you done that – jamylak Apr 10 '13 at 11:54
  • @Wooble: bound methods are first class citizens in the Python world and there are very obvious reasons to "pass around" bound methods instead of instances - like, say, as a callback... Now I agree that except for 1/ debugging and 2/ a very few corner cases I don't see much reason to try and find the class of the bound instance. – bruno desthuilliers Apr 10 '13 at 13:37
  • @brunodesthuilliers: Indeed that was for debugging reasons. – running.t Apr 10 '13 at 14:12

1 Answers1

7

If you want the name of it:

boundmethod.im_class.__name__

Or in python 3:

boundmethod.__self__.__class__.__name__
Erik Aronesty
  • 11,620
  • 5
  • 64
  • 44
jamylak
  • 128,818
  • 30
  • 231
  • 230
  • 1
    Hello - just looking for some clarification; if `boundmethod` is attached to an instance that has an inheritance hierarchy, and `boundmethod` exists towards the bottom of that hierarchy, will `boundmethod.im_class` point to the class that defined it, or will it point to `boundmethod`'s class? – Gershom Maes Oct 01 '15 at 17:12
  • @GershomMaes I believe it should point to `boundmethod`'s class If I've interpreted you correctly – jamylak Oct 01 '15 at 17:43