tags:

views:

161

answers:

4

How can I get the parent(s) object of python class?

+3  A: 

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'>)
Ayman Hourieh
+3  A: 

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;-).

Alex Martelli
+1  A: 

If you want to ensure they all get called, use super at all levels.

Mike Graham
Once you use super you have to use it in all levels anyway, which is why you should document it's use explicitly. Also you might want to know that super doesn't work on every class...
DasIch
A: 

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

DasIch