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
2010-04-10 01:35:02
+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
2010-04-10 02:00:17
+1
A:
If you want to ensure they all get called, use super
at all levels.
Mike Graham
2010-04-10 02:29:37
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
2010-04-10 03:57:36
A:
New-style classes have an mro method you can call which returns a list of parent classes in method resolution order.
DasIch
2010-04-10 03:56:04