Is there way to determine which class a method is bound to?
Robin Becker
robin at reportlab.com
Fri Feb 25 11:04:12 EST 2005
Victor Ng wrote:
> I'm doing some evil things in Python and I would find it useful to
> determine which class a method is bound to when I'm given a method
> pointer.
>
> For example:
>
> class Foo(object):
> def somemeth(self):
> return 42
>
> class Bar(Foo):
> def othermethod(self):
> return 42
>
>
> Is there some way I can have something like :
>
> findClass(Bar.somemeth)
>
> that would return the 'Foo' class, and
>
> findClass(Bar.othermethod)
>
> would return the 'Bar' class?
>
> vic
I think you can use the mro function
>>> class Foo(object):
... def somemeth(self):
... pass
...
>>> class Bar(Foo):
... def othermeth(self):
... pass
...
>>> def findClass(meth):
... for x in meth.im_class.mro():
... if meth.im_func in x.__dict__.values(): return x
...
>>> findClass(Bar.somemeth)
<class '__main__.Foo'>
>>> findClass(Bar.othermeth)
<class '__main__.Bar'>
>>>
--
Robin Becker
More information about the Python-list
mailing list