Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the parents of a Python class?

Tags:

python

oop

People also ask

How do you find the parent class in Python?

The fastest way to get all parents, and in order, is to just use the __mro__ built-in. For instance, repr(YOUR_CLASS. __mro__) . There you have it.

How do you inherit parent methods in Python?

Use the super() Function By using the super() function, you do not have to use the name of the parent element, it will automatically inherit the methods and properties from its parent.

What is the parent class of parent class?

In the object-oriented programming, we can inherit the characteristics of parent class. Parent class is known as base class while child class is known as derived class.

What does super () __ Init__ do?

Understanding Python super() with __init__() methods It is known as a constructor in Object-Oriented terminology. This method when called, allows the class to initialize the attributes of the class. The super() function allows us to avoid using the base class name explicitly.


Use the following attribute:

cls.__bases__

From the docs:

The tuple of base classes of a class object.

Example:

>>> str.__bases__
(<type 'basestring'>,)

Another example:

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

If you want all the ancestors rather than just the immediate ones, 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;-).


The fastest way to get all parents, and in order, is to just use the __mro__ built-in.

For instance, repr(YOUR_CLASS.__mro__).

The following:

import getpass
getpass.GetPassWarning.__mro__

...outputs, in order:

(<class 'getpass.GetPassWarning'>, <type 'exceptions.UserWarning'>, <type 'exceptions.Warning'>, <type 'exceptions.Exception'>, <type 'exceptions.BaseException'>, <type 'object'>)

There you have it. The "best" answer may have more votes but this is so much simpler than some convoluted for loop, looking into __bases__ one class at a time, not to mention when a class extends two or more parent classes. Importing and using inspect just clouds the scope unnecessarily.


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