0

Let's say I have the following code:

class A:
    pass

class B(A):
    pass

class C(B):
    pass

obj = C()

Then, obj is an instance of all three classes A, B, and C. This can be verified by calling isinstance(obj, cls).

Is there a way to do the inverse, that is to have a function which returns a list of all classes that an object is an instance of?

So, isinstanceof(obj) would return [A, B, C].

XYZT
  • 605
  • 5
  • 17
  • 1
    Technically speaking, `obj` is an instance of class C who inherits from B (who in turn inherits from A). Having said that there is a method to check if a class is a subclass (see [this](https://stackoverflow.com/questions/5628084/test-if-a-class-is-inherited-from-another) question) As far as I know there is no built in method to get the parent, but you can create a method in each subclass to get the parent (see answer [here](https://stackoverflow.com/questions/10091957/get-parent-class-name) – nickyfot Oct 29 '19 at 12:46

2 Answers2

3

You want the Method Resolution Order, which you can get via the class.

obj.__class__.__mro__
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
2

The closest you can get is to traverse the method resolution order (MRO) on the type of obj (which is C):

type(obj).__mro__

would give you:

(__main__.C, __main__.B, __main__.A, object)

You can also call the mro method instead of using the dunder __mro__ attribute on the type:

type(obj).mro()
heemayl
  • 39,294
  • 7
  • 70
  • 76