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

Peter Otten __peter__ at web.de
Fri Feb 25 10:42:00 EST 2005


Peter Otten wrote:

>>>> 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

I think it might be better to demonstrate the problem than just to describe
it:

>>> def another(self): pass
...
>>> Foo.alpha = another
>>> Bar.beta = another
>>> get_imp_class(Bar.alpha)
<class '__main__.Foo'>
>>> get_imp_class(Bar.beta)
<class '__main__.Foo'>

A name check won't help either:

>>> Foo.alpha.__name__
'another'

Peter




More information about the Python-list mailing list