Is there way to determine which class a method is bound to?

Victor Ng crankycoder at gmail.com
Fri Feb 25 10:39:56 EST 2005


Awesome!  I didn't see the getmro function in inspect - that'll do the
trick for me.  I should be able to just look up the methodname in each
of the class's __dict__ attributes.

vic


On Fri, 25 Feb 2005 16:29:25 +0100, Peter Otten <__peter__ at web.de> wrote:
> 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
> 
> >>> import inspect
> >>> class Foo(object):
> ...     def foo(self): pass
> ...
> >>> class Bar(Foo):
> ...     def bar(self): pass
> ...
> >>> def get_imp_class(method):
> ...     return [t for t in inspect.classify_class_attrs(method.im_class) if
> t[-1] is method.im_func][0][2]
> ...
> >>> [get_imp_class(m) for m in [Bar().foo, Bar().bar, Bar.foo, Bar.bar]]
> [<class '__main__.Foo'>, <class '__main__.Bar'>, <class '__main__.Foo'>,
> <class '__main__.Bar'>]
> 
> but with this approach you will get into trouble as soon as you are using
> the same function to define multiple methods. There may be something in the
> inspect module more apt to solve the problem -- getmro() perhaps?
> 
> Peter
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list