inheritance - In Python, class from which a given instance is inheriting a particular method -
i know in python, given class classa
,
inspect.getmembers(classa, predicate=inspect.ismethod)
i can iterate on different methods present in classa
. inherited methods gathered, convenient in case. need is, given particular method method1
of classa
, class classa
inherited method1
. might classa
itself, or of parents/grandparents. thought recursively traverse __bases__
attribute, looking method1
attribute @ each step. maybe functionality implemented somewhere. there way?
look through mro (method resolution order), using inspect.getmro()
(which works on both old , new-style classes):
def class_for_method(cls, method): return next((c c in inspect.getmro(cls) if method.__func__ in vars(c).values()), none)
there no stdlib method search you, no.
demo:
>>> import inspect >>> def class_for_method(cls, method): ... return next((c c in inspect.getmro(cls) ... if method.__func__ in vars(c).values()), none) ... >>> class base1(object): ... def foo(self): pass ... >>> class base2(object): ... pass ... >>> class classa(base1, base2): ... pass ... >>> class_for_method(classa, classa.foo) <class '__main__.base1'>
if no base class found, above expression returns none
:
>>> class bar: ... def spam(): pass ... >>> class_for_method(classa, bar.spam) none true
Comments
Post a Comment