Resolving declaring class of a method at runtime

Duncan Booth duncan.booth at invalid.invalid
Thu Nov 15 09:05:21 EST 2007


"Janne Härkönen" <janne.t.harkonen at gmail.com> wrote:

> $ python
> Python 2.5.1 (r251:54863, May 18 2007, 16:56:43)
> [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin
> Type "help", "copyright", "credits" or "license" for more information.
>>>> class X:
> ...   def x(self):
> ...    pass
> ...
>>>> class Y(X):
> ...   def y(self):
> ...    pass
> ...
>>>> y = Y()
>>>> y.x.im_class
><class __main__.Y at 0x7ff24bfc>
>>>> y.y.im_class
><class __main__.Y at 0x7ff24bfc>
> 
> What I would like to find out is the declaring class of method x, ie.
> class X How to do this ?
> 

For what it is worth, this should work for simple cases:

>>> def searchclass(K, name):
	for base in getattr(K, '__mro__', (K,)+K.__bases__):
		if name in base.__dict__:
			return base

		
>>> searchclass(Y, 'y')
<class __main__.Y at 0x00C4FE40>
>>> searchclass(Y, 'x')
<class __main__.X at 0x00C4FE70>



More information about the Python-list mailing list