Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List all base classes in a hierarchy of given class?

People also ask

What is the base class of all classes in Python?

Metaclass in Python Thus, the type class is the metaclass of int and float classes. The type class is even the metaclass for the built-in object class, which is the base class for all the classes in Python.

What is hierarchy of classes in inheritance?

Hierarchical inheritance is a kind of inheritance where more than one class is inherited from a single parent or base class. Especially those features which are common in the parent class is also common with the base class.

What is class hierarchy in C#?

A type of inheritance in which more than one class is inherited from a single parent or base class is known as hierarchical inheritance. The base class shares many of the same properties as the parent class, especially those that are common in the parent class.

How do you list members of a class in Python?

Using the dir() method to find all the class attributes It returns a list of the attributes and methods of the passed object/class. On being called upon class objects, it returns a list of names of all the valid attributes and base attributes too. Syntax: dir(object) , where object is optional.


inspect.getmro(cls) works for both new and old style classes and returns the same as NewClass.mro(): a list of the class and all its ancestor classes, in the order used for method resolution.

>>> class A(object):
>>>     pass
>>>
>>> class B(A):
>>>     pass
>>>
>>> import inspect
>>> inspect.getmro(B)
(<class '__main__.B'>, <class '__main__.A'>, <type 'object'>)

See the __bases__ property available on a python class, which contains a tuple of the bases classes:

>>> def classlookup(cls):
...     c = list(cls.__bases__)
...     for base in c:
...         c.extend(classlookup(base))
...     return c
...
>>> class A: pass
...
>>> class B(A): pass
...
>>> class C(object, B): pass
...
>>> classlookup(C)
[<type 'object'>, <class __main__.B at 0x00AB7300>, <class __main__.A at 0x00A6D630>]

inspect.getclasstree() will create a nested list of classes and their bases. Usage:

inspect.getclasstree(inspect.getmro(IOError)) # Insert your Class instead of IOError.

you can use the __bases__ tuple of the class object:

class A(object, B, C):
    def __init__(self):
       pass
print A.__bases__

The tuple returned by __bases__ has all its base classes.