Finding in which class an object's method comes from

dieter dieter at handshake.de
Fri Feb 5 02:52:04 EST 2016


"ast" <nomail at invalid.com> writes:
> Suppose we have:
>
> ClassC inherit from ClassB
> ClassB inherit from ClassA
> ClassA inherit from object
>
> Let's build an object:
>
> obj = ClassC()
>
> Let's invoke an obj method
>
> obj.funct()
>
> funct is first looked in ClassC, then if not found
> on ClassB, then ClassA then object

In Python 2, I am using the following function to find out such
information.

from inspect import getmro

def definedBy(name, class_):
  '''return *class_* base class defining *name*.

  *class_* may (now) also be an object. In this case, its class is used.
  '''
  if not hasattr(class_, '__bases__'): class_ = class_.__class__
  for cl in getmro(class_):
    if hasattr(cl,'__dict__'):
      if cl.__dict__.has_key(name): return cl
    elif hasattr(cl, name): return cl
  return None
  
(Unlike other approaches reported in this thread)
it not only works for methods but also for other attributes.

I am using this for (interactive) debugging purposes:
usually, I work with Zope/Plone which is a huge software stack
and their it is handy to be able to quickly find out where something
is defined in the code.




More information about the Python-list mailing list