The Python Oracle

How to get the parents of a Python class?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Luau

--

Chapters
00:00 How To Get The Parents Of A Python Class?
00:08 Accepted Answer Score 364
00:33 Answer 2 Score 146
01:01 Answer 3 Score 20
01:13 Answer 4 Score 20
01:52 Thank you

--

Full question
https://stackoverflow.com/questions/2611...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #oop

#avk47



ACCEPTED ANSWER

Score 364


Use the following attribute:

cls.__bases__

From the docs:

The tuple of base classes of a class object.

Example:

>>> str.__bases__
(<class 'object'>,)

Another example:

>>> class A(object):
...   pass
... 
>>> class B(object):
...   pass
... 
>>> class C(A, B):
...   pass
... 
>>> C.__bases__
(<class '__main__.A'>, <class '__main__.B'>)



ANSWER 2

Score 146


If you want all the ancestors rather than just the immediate ones, use cls.__mro__.

For versions of Python earlier than 3.5, use inspect.getmro:

import inspect
print inspect.getmro(cls)

Usefully, this gives you all ancestor classes in the "method resolution order" -- i.e. the order in which the ancestors will be checked when resolving a method (or, actually, any other attribute -- methods and other attributes live in the same namespace in Python, after all;-).




ANSWER 3

Score 20


New-style classes have an mro method you can call which returns a list of parent classes in method resolution order.




ANSWER 4

Score 20


Use bases if you just want to get the parents, use __mro__ (as pointed out by @naught101) for getting the method resolution order (so to know in which order the init's were executed).

Bases (and first getting the class for an existing object):

>>> some_object = "some_text"
>>> some_object.__class__.__bases__
(object,)

For mro in recent Python versions:

>>> some_object = "some_text"
>>> some_object.__class__.__mro__
(str, object)

Obviously, when you already have a class definition, you can just call __mro__ on that directly:

>>> class A(): pass
>>> A.__mro__
(__main__.A, object)