introspection - How to check in Python from which class methods is derived? -
i have 2 classes:
class a(object): def a(self): pass class b(a): def b(self): pass print dir(a) print dir(b)
how can check class methods derived in python?
for example:
getmethodclass(a.a) == getmethodclass(b.a) == getmethodclass(b.b) == b
interesting question. here how i'd go it.
(this works in python2. haven't tested in python3, won't surprised if not work...)
you can iterate on "nominees" using reversed(inspect.getmro(cls))
, , returning first (by fetching next
value of iterator) satisfy condition has relevant attr
, , attr
same method of relevant cls
.
method identity-comparison done comparing im_func
attribute of unbound method.
import inspect def getmethodclass(cls, attr): return next( basecls basecls in reversed(inspect.getmro(cls)) if hasattr(basecls, attr) , getattr(basecls, attr).im_func getattr(cls, attr).im_func ) getmethodclass(a, 'a') => __main__.a getmethodclass(b, 'a') => __main__.a getmethodclass(b, 'b') => __main__.b # alternative implementation, suggested @chameleon def getattributeclass(cls, attrname): # check first if has attribute attr = getattr(cls, attrname) mro = inspect.getmro(cls) # 1 class on list if len(mro) == 1: return cls # many class on list base in reversed(mro[1:]): # check if defined in base try: baseattr = getattr(base, attrname) except attributeerror: continue else: if baseattr.im_func attr.im_func: return base # define in top class return cls
the function can have signature suggest:
def getmethodclass(unbound_method): cls = unbound_method.im_class attr = unbound_method.__name__ # rest of implementation same before... getmethodclass(b.a) => __main__.a
Comments
Post a Comment